<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"always","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="郭鹏松的个人博客">
<meta property="og:type" content="website">
<meta property="og:title" content="Albert Guo">
<meta property="og:url" content="http://yoursite.com/index.html">
<meta property="og:site_name" content="Albert Guo">
<meta property="og:description" content="郭鹏松的个人博客">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="Albert Guo">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://yoursite.com/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : true,
    isPost : false,
    lang   : 'zh-CN'
  };
</script>

  <title>Albert Guo</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Albert Guo</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-bars fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-address-card fa-fw"></i>简介</a>

  </li>
        <li class="menu-item menu-item-webpack">

    <a href="/webpack/" rel="section"><i class="fa fa-bookmark fa-fw"></i>webpack</a>

  </li>
        <li class="menu-item menu-item-javascript">

    <a href="/JavaScript/" rel="section"><i class="fa fa-bookmark fa-fw"></i>ECMAScript 5.1</a>

  </li>
        <li class="menu-item menu-item-ecmascript6">

    <a href="/ECMAScript6/" rel="section"><i class="fa fa-bookmark fa-fw"></i>ECMAScript 6</a>

  </li>
        <li class="menu-item menu-item-react">

    <a href="/React/" rel="section"><i class="fa fa-bookmark fa-fw"></i>React</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content index posts-expand">
            
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/11/23/webpack5-%E6%9B%B4%E6%96%B0%E6%97%A5%E5%BF%97/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://inews.gtimg.com/newsapp_ls/0/12122532695/0">
      <meta itemprop="name" content="Albert Guo">
      <meta itemprop="description" content="郭鹏松的个人博客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Albert Guo">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2020/11/23/webpack5-%E6%9B%B4%E6%96%B0%E6%97%A5%E5%BF%97/" class="post-title-link" itemprop="url">webpack5 更新日志</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-11-23 20:31:33 / 修改时间：20:42:08" itemprop="dateCreated datePublished" datetime="2020-11-23T20:31:33+08:00">2020-11-23</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/webpack/" itemprop="url" rel="index"><span itemprop="name">webpack</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <blockquote>
<p>文章转载自网络，仅供参考学习。<br>作者：河马（前端/Node.js/Java。公众号：进击的前端101), 原文地址：<a href="https://zhuanlan.zhihu.com/p/264826929" target="_blank" rel="noopener">https://zhuanlan.zhihu.com/p/264826929</a></p>
</blockquote>
<p>webpack 作为最使用最广泛的前端打包工具，已经成为前端工程化基础设施的一部分。而 Webpack 上一个大版本更新已经是18年的时候了，两年时间过去了让我们看看Webpack5 都带来了哪些新特性，对我们的应用又有哪些帮助。</p>
<h1 id="概览"><a href="#概览" class="headerlink" title="概览"></a>概览</h1><p>下面这张图是 Webpack 官方 Changelog 里面截图出来的，可以看到主要有这些方面的提高：</p>
<ul>
<li>通过持久化缓存提高性能</li>
<li>采用更好的持久化缓存算法和默认行为</li>
<li>通过优化 Tree Shaking 和代码生成来减小Bundle体积</li>
<li>提高 Web 平台的兼容性</li>
<li>清除之前为了实现 Webpack4 没有不兼容性变更导致的不合理 state</li>
<li>尝试现在引入重大更改来为将来的功能做准备，以使我们能够尽可能长时间地使用 Webpack 5</li>
</ul>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20201123203814.jpg" alt="官方更新日志"></p>
<p>不得不说，这个官方声明稍微简略了一点，只提到了持久化缓存优化性能和更好的 Tree Shaking，Module federation 这个重大特性居然提都没有提。下面还是跟着小编看看具体都升级了哪些部分。</p>
<h1 id="过时功能移除"><a href="#过时功能移除" class="headerlink" title="过时功能移除"></a>过时功能移除</h1><ul>
<li>首先是去掉了在 Webpack4 里面已经 Warning 的功能。</li>
<li>同时 IgnorePlugin 和 BannerPlugin 现在必须传入一个参数，参数可以是 Object、String或者Function</li>
<li>require.include 语法被废弃，使用时会有 Warning。当然这个行为可以通过 Rule.parser.requireInclude 来把这个语法改成 allowed, deprecated 或者 disabled</li>
<li>去掉自动 Node.js Polyfills 。早期 Webpack 的主要目的是让 Node.js 的模块能够在浏览器运行，但随着模块格局的改变，越来越多的模块只用于浏览器，这个时候再自动 Polyfills 一些 Node 模块（例如 crypto）无疑会增加打包体积，在 Webpack5 之后去掉了这个自动行为</li>
</ul>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/09/02/React-Router-%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://inews.gtimg.com/newsapp_ls/0/12122532695/0">
      <meta itemprop="name" content="Albert Guo">
      <meta itemprop="description" content="郭鹏松的个人博客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Albert Guo">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2020/09/02/React-Router-%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B/" class="post-title-link" itemprop="url">web 端 React Router 使用教程</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-09-02 17:55:40" itemprop="dateCreated datePublished" datetime="2020-09-02T17:55:40+08:00">2020-09-02</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-09-23 22:01:53" itemprop="dateModified" datetime="2020-09-23T22:01:53+08:00">2020-09-23</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/react/" itemprop="url" rel="index"><span itemprop="name">react</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>React Router 其实并不复杂，官方的 API 也就短短几页，入门使用并不困难。国内的相关文档、博客鱼龙混杂，复制粘贴，抄袭严重，甚至很多是拿翻译软件直译过来的，语句都不通顺，反而会误导初学者。强烈建议有能力的读者还是直接访问官方文档。</p>
<p>本文并非对官方文档 API 的直接翻译，更多的是阐述说明，助于理解。想要更深入研究的，还是建议直接访问官方文档。</p>
<blockquote>
<p>官方文档地址：<a href="https://reactrouter.com/web/guides/quick-start" target="_blank" rel="noopener">https://reactrouter.com/web/guides/quick-start</a></p>
</blockquote>
<h1 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h1><p>React Router 是官方推荐的库，它通过管理 URL，实现组件的切换和状态的变化，本文只阐述 web 端的相关使用。</p>
<p>开发环境推荐直接采用 Create React App 脚手架工具搭建，具体搭建方法就不在赘述。</p>
<h1 id="react-router-与-react-router-dom"><a href="#react-router-与-react-router-dom" class="headerlink" title="react-router 与 react-router-dom"></a>react-router 与 react-router-dom</h1><p>有些项目中会看到引用了 <code>react-router</code> 库 ，也有的用了 <code>react-router-dom</code> 库。甚至在官方的文档教程中的案例，针对相同的组件，也出现了引入不同库的情况。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 引入库 &quot;react-router&quot;</span><br><span class="line">import &#123; Route, Switch &#125; from &quot;react-router&quot;;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 引入库 &quot;react-router-dom&quot;</span><br><span class="line">import &#123;</span><br><span class="line">  BrowserRouter as Router,</span><br><span class="line">  Switch,</span><br><span class="line">  Route,</span><br><span class="line">  useParams</span><br><span class="line">&#125; from &quot;react-router-dom&quot;;</span><br></pre></td></tr></table></figure>

<p>两者有何区别呢？</p>
<p>先简单说下各自的功能：</p>
<ul>
<li><code>react-router</code>：是路由核心功能的实现库</li>
<li><code>react-router-dom</code>：基于 <code>react-router</code>，加入了在浏览器运行环境下的一些功能，例如：<code>Link</code> 组件、<code>BrowserRouter</code> 和 <code>HashRouter</code>  组件等。</li>
<li><code>react-router-native</code>：基于 <code>react-router</code>，类似 <code>react-router-dom</code>，加入了 <code>react-native</code> 运行环境下的一些功能，本文不涉及。</li>
</ul>
<p><code>react-router-dom</code> 依赖 <code>react-router</code>，所以使用 <code>npm</code> 安装依赖的时候，只需要安装相应环境下的库即可，不用再显式安装 <code>react-router</code>。例如，基于浏览器环境的开发，只需要安装 <code>react-router-dom</code>，<code>npm</code> 会自动解析 <code>react-router-dom</code> 包中 <code>package.json</code> 的依赖并安装。</p>
<p><code>react-router</code> 实现了路由的核心功能，可以理解为第四代，就是 <code>v4</code> 的版本。<code>react-router-dom</code> 可以理解为第五代。一般目前环境下，web 端开发都直接使用的 <code>react-router-dom</code>，一些常用的组件都封装好了。</p>
<h1 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h1><p>假定已经使用 Create React App 初始化了 React 项目。</p>
<p>需要单独对 <code>react-router-dom</code> 库进行安装。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">npx create-react-app demo-app</span><br><span class="line">cd demo-app</span><br><span class="line">Installation</span><br><span class="line">...</span><br><span class="line">npm install react-router-dom</span><br></pre></td></tr></table></figure>

<h1 id="基本路由"><a href="#基本路由" class="headerlink" title="基本路由"></a>基本路由</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">import React from &#39;react&#39;;</span><br><span class="line">import &#123;BrowserRouter as Router, Link, Route, Switch&#125; from &#39;react-router-dom&#39;;</span><br><span class="line"></span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;Router&gt;</span><br><span class="line">            &lt;ul&gt;</span><br><span class="line">                &lt;li&gt;</span><br><span class="line">                    &lt;Link to&#x3D;&#39;&#x2F;&#39;&gt;首页&lt;&#x2F;Link&gt;</span><br><span class="line">                &lt;&#x2F;li&gt;</span><br><span class="line">                &lt;li&gt;</span><br><span class="line">                    &lt;Link to&#x3D;&#39;&#x2F;user&#39;&gt;用户&lt;&#x2F;Link&gt;</span><br><span class="line">                &lt;&#x2F;li&gt;</span><br><span class="line">                &lt;li&gt;</span><br><span class="line">                    &lt;Link to&#x3D;&#39;&#x2F;about&#39;&gt;关于&lt;&#x2F;Link&gt;</span><br><span class="line">                &lt;&#x2F;li&gt;</span><br><span class="line">            &lt;&#x2F;ul&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39;&gt;&lt;User&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39;&gt;&lt;About&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;&#39;&gt;&lt;Home&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;Router&gt;</span><br><span class="line">        )</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function Home() &#123;</span><br><span class="line">    return &lt;div&gt;Home&lt;&#x2F;div&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function About() &#123;</span><br><span class="line">    return &lt;div&gt;About&lt;&#x2F;div&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function User() &#123;</span><br><span class="line">    return &lt;div&gt;User&lt;&#x2F;div&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">export default App;</span><br></pre></td></tr></table></figure>

<p>这里的 <code>BrowserRouter as Router, Link, Route, Switch</code> 相关属性方法先不做说明，后续会陆续解释。先看配置代码以及效果。</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200823154231.gif" alt="基本路由效果"></p>
<p>简单了解一下该案例：</p>
<ol>
<li>路由配置必须放在一个 <code>&lt;Router&gt;</code> 根组件下边，这个例子中其实是将 <code>&lt;BrowserRouter&gt;</code> 重命名为了 <code>&lt;Router&gt;</code>。</li>
<li>每个路由的模块必须由 <code>&lt;Route&gt;</code> 包裹。</li>
<li>这里的路由，采用了 <code>&lt;Switch&gt;</code> 匹配，从上到下，单个匹配。</li>
</ol>
<h1 id="嵌套路由"><a href="#嵌套路由" class="headerlink" title="嵌套路由"></a>嵌套路由</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line">import React from &quot;react&quot;;</span><br><span class="line">import &#123;</span><br><span class="line">    BrowserRouter as Router,</span><br><span class="line">    Switch,</span><br><span class="line">    Route,</span><br><span class="line">    Link,</span><br><span class="line">    useRouteMatch,</span><br><span class="line">    useParams</span><br><span class="line">&#125; from &quot;react-router-dom&quot;;</span><br><span class="line"></span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;Router&gt;</span><br><span class="line">            &lt;ul&gt;</span><br><span class="line">                &lt;li&gt;</span><br><span class="line">                    &lt;Link to&#x3D;&#39;&#x2F;&#39;&gt;首页&lt;&#x2F;Link&gt;</span><br><span class="line">                &lt;&#x2F;li&gt;</span><br><span class="line">                &lt;li&gt;</span><br><span class="line">                    &lt;Link to&#x3D;&#39;&#x2F;about&#39;&gt;关于&lt;&#x2F;Link&gt;</span><br><span class="line">                &lt;&#x2F;li&gt;</span><br><span class="line">                &lt;li&gt;</span><br><span class="line">                    &lt;Link to&#x3D;&#39;&#x2F;topics&#39;&gt;话题&lt;&#x2F;Link&gt;</span><br><span class="line">                &lt;&#x2F;li&gt;</span><br><span class="line">            &lt;&#x2F;ul&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;topics&#39;&gt;&lt;Topics&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39;&gt;&lt;About&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;&#39;&gt;&lt;Home&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;Router&gt;</span><br><span class="line">        )</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function Home() &#123;</span><br><span class="line">    return &lt;div&gt;首页&lt;&#x2F;div&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function About() &#123;</span><br><span class="line">    return &lt;div&gt;关于&lt;&#x2F;div&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 话题组件是一个嵌套路由</span><br><span class="line">function Topics() &#123;</span><br><span class="line">    let match &#x3D; useRouteMatch();</span><br><span class="line">    return (</span><br><span class="line">        &lt;div&gt;</span><br><span class="line">            &lt;h2&gt;话题&lt;&#x2F;h2&gt;</span><br><span class="line">            &lt;ul&gt;</span><br><span class="line">                &lt;li&gt;</span><br><span class="line">                    &lt;Link to&#x3D;&#123;&#96;$&#123;match.url&#125;&#x2F;topic1&#96;&#125;&gt;话题1&lt;&#x2F;Link&gt;</span><br><span class="line">                &lt;&#x2F;li&gt;</span><br><span class="line">                &lt;li&gt;</span><br><span class="line">                    &lt;Link to&#x3D;&#123;&#96;$&#123;match.url&#125;&#x2F;topic2&#96;&#125;&gt;话题2&lt;&#x2F;Link&gt;</span><br><span class="line">                &lt;&#x2F;li&gt;</span><br><span class="line">            &lt;&#x2F;ul&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#123;&#96;$&#123;match.path&#125;&#x2F;:topicId&#96;&#125;&gt;</span><br><span class="line">                    &lt;Topic&#x2F;&gt;</span><br><span class="line">                &lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;div&gt;</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function Topic() &#123;</span><br><span class="line">    let &#123;topicId&#125; &#x3D; useParams();</span><br><span class="line">    return &lt;h3&gt;获取话题 ID 为: &#123;topicId&#125;&lt;&#x2F;h3&gt;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">export default App;</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200823154258.gif" alt="嵌套路由效果"></p>
<p>第一层的路由其实跟基本路由配置一样。嵌套路由的 <code>&lt;Topics&gt;</code> 组件，需要在其内部再次配置路由。这里运用了 <code>useRouteMatch、useParams</code> 内置方法，后面会在 API 中介绍，主要用于路径获取、参数获取等功能。</p>
<h1 id="基本组件"><a href="#基本组件" class="headerlink" title="基本组件"></a>基本组件</h1><p>路由的基本组件大致可以分为三类：</p>
<ol>
<li>routers（路由集合）：例如 <code>&lt;BrowserRouter&gt;</code>、<code>&lt;HashRouter&gt;</code> 等</li>
<li>route matchers（路由匹配）：例如 <code>&lt;Route&gt;</code>、<code>&lt;Switch&gt;</code> 等</li>
<li>navigation（导航跳转）：例如 <code>&lt;Link&gt;</code>、<code>&lt;NavLink&gt;</code>、<code>&lt;Redirect&gt;</code> 等</li>
</ol>
<p>这些所有的组件都需要在项目中提前安装并引入 <code>react-router-dom</code>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">import &#123; BrowserRouter, Route, Link &#125; from &quot;react-router-dom&quot;;</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="Hooks"><a href="#Hooks" class="headerlink" title="Hooks"></a>Hooks</h1><p><code>React Router</code> 附带几个钩子函数，允许访问路由器的状态并从内部执行导航组件。请注意：需要使用<code>React&gt;=16.8</code> 才能使用这些钩子！</p>
<p>useHistory<br>useLocation<br>useParams<br>useRouteMatch</p>
<hr>
<h1 id=""><a href="#" class="headerlink" title=""></a><BrowserRouter></h1><p><code>&lt;BrowserRouter&gt;</code> 使用 HTML5 提供的 history API (<code>pushState</code>, <code>replaceState</code> 和 <code>popstate</code> 事件) 来保持 UI 和 URL 的同步。该组件提供了几个内置属性，可以实现不同功能需求。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;BrowserRouter</span><br><span class="line">  basename&#x3D;&#123;optionalString&#125;</span><br><span class="line">  forceRefresh&#x3D;&#123;optionalBool&#125;</span><br><span class="line">  getUserConfirmation&#x3D;&#123;optionalFunc&#125;</span><br><span class="line">  keyLength&#x3D;&#123;optionalNumber&#125;</span><br><span class="line">&gt;</span><br><span class="line">  &lt;App &#x2F;&gt;</span><br><span class="line">&lt;&#x2F;BrowserRouter&gt;</span><br></pre></td></tr></table></figure>

<h2 id="basename-string"><a href="#basename-string" class="headerlink" title="basename: string"></a>basename: string</h2><p>该属性可以理解为所有路径的基础路径，属性值为字符串。</p>
<p>如果应用程序是从服务器上的子目录中提供的，则需要将其设置为子目录。格式正确的 <code>basename</code> 应该有一个前导斜杠，但没有尾随斜杠。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">import React from &quot;react&quot;;</span><br><span class="line">import &#123;BrowserRouter, Link, Route, Switch&#125; from &quot;react-router-dom&quot;;</span><br><span class="line"></span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter basename&#x3D;&quot;&#x2F;test&quot;&gt;</span><br><span class="line">            &lt;Link to&#x3D;&quot;&#x2F;home&quot;&gt;首页&lt;&#x2F;Link&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;Link to&#x3D;&quot;&#x2F;user&quot;&gt;用户&lt;&#x2F;Link&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;Link to&#x3D;&quot;&#x2F;about&quot;&gt;关于&lt;&#x2F;Link&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39;&gt;&lt;User&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39;&gt;&lt;About&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;home&#39;&gt;&lt;Home&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function Home() &#123;</span><br><span class="line">    return &lt;div&gt;首页&lt;&#x2F;div&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function User() &#123;</span><br><span class="line">    return &lt;div&gt;用户&lt;&#x2F;div&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function About() &#123;</span><br><span class="line">    return &lt;div&gt;关于&lt;&#x2F;div&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">export default App;</span><br></pre></td></tr></table></figure>

<p>实现效果，注意观察 URL 的变化。</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200827170945.gif" alt="basename 属性效果"></p>
<h2 id="getUserConfirmation-func"><a href="#getUserConfirmation-func" class="headerlink" title="getUserConfirmation: func"></a>getUserConfirmation: func</h2><p>导航到此页面前执行的函数，默认使用 <code>window.confirm</code>。当需要用户进入页面前执行某些操作时可用，应用场景不多，详细用法请查阅文档。</p>
<h2 id="forceRefresh-bool"><a href="#forceRefresh-bool" class="headerlink" title="forceRefresh: bool"></a>forceRefresh: bool</h2><p>布尔值，用于控制路由切换是否刷新当前页面，默认为 <code>false</code>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"> function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter basename&#x3D;&quot;&#x2F;test&quot; forceRefresh&#x3D;&#123;false&#125;&gt;</span><br><span class="line">            &lt;Link to&#x3D;&quot;&#x2F;home&quot;&gt;首页&lt;&#x2F;Link&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;Link to&#x3D;&quot;&#x2F;user&quot;&gt;用户&lt;&#x2F;Link&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;Link to&#x3D;&quot;&#x2F;about&quot;&gt;关于&lt;&#x2F;Link&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39;&gt;&lt;User&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39;&gt;&lt;About&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;home&#39;&gt;&lt;Home&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>设置为 <code>false</code> 时，页面地址切换不刷新页面，注意观察网页头。</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200827193340.gif" alt="不刷新效果"></p>
<p>设置为 <code>true</code> 时，路由切换会强制刷新页面，注意观察网页头。</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200827193251.gif" alt="刷新效果"></p>
<h2 id="keyLength-number"><a href="#keyLength-number" class="headerlink" title="keyLength: number"></a>keyLength: number</h2><p>官网直译为 <code>location.key</code> 的长度，默认为 <code>6</code>，官网也没有太多介绍，个人查了很多资料，也没查到相关介绍。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;BrowserRouter keyLength&#x3D;&#123;12&#125; &#x2F;&gt;</span><br></pre></td></tr></table></figure>

<h1 id="-1"><a href="#-1" class="headerlink" title=""></a><HashRouter></h1><p><code>&lt;HashRouter&gt;</code> 功能与 <code>&lt;BrowserRouter&gt;</code> 一样，用法也基本相同，但是原理不同。<code>&lt;HashRouter&gt;</code> 使用 URL 的 <code>hash</code> 部分（即 <code>window.location.hash</code>）来保持 UI 和 URL 的同步。因此 URL 看起来类似于 <code>http://example.com/#/your/page.</code>。由于哈希从不发送到服务器，意味着不需要特殊的服务器配置。</p>
<p>目前实际工作中来说，大部分场景下还是使用 <code>&lt;BrowserRouter&gt;</code> 多一些。</p>
<p>设置效果如下，注意观察 URL 地址栏的参数编码。</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200827205638.gif" alt="哈希路由效果"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">import React from &quot;react&quot;;</span><br><span class="line">import &#123;HashRouter, Link, Route, Switch&#125; from &quot;react-router-dom&quot;;</span><br><span class="line"></span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;HashRouter basename&#x3D;&quot;&#x2F;test&quot;&gt;</span><br><span class="line">            &lt;Link to&#x3D;&quot;&#x2F;home&quot;&gt;首页&lt;&#x2F;Link&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;Link to&#x3D;&quot;&#x2F;user&quot;&gt;用户&lt;&#x2F;Link&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;Link to&#x3D;&quot;&#x2F;about&quot;&gt;关于&lt;&#x2F;Link&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39;&gt;&lt;User&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39;&gt;&lt;About&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;home&#39;&gt;&lt;Home&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;HashRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function Home() &#123;</span><br><span class="line">    return &lt;div&gt;首页&lt;&#x2F;div&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function User() &#123;</span><br><span class="line">    return &lt;div&gt;用户&lt;&#x2F;div&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function About() &#123;</span><br><span class="line">    return &lt;div&gt;关于&lt;&#x2F;div&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">export default App;</span><br></pre></td></tr></table></figure>

<h2 id="basename-string-1"><a href="#basename-string-1" class="headerlink" title="basename: string"></a>basename: string</h2><p>参照 <code>&lt;BrowserRouter&gt;</code> 中该属性用法，基本相同。</p>
<h2 id="getUserConfirmation-func-1"><a href="#getUserConfirmation-func-1" class="headerlink" title="getUserConfirmation: func"></a>getUserConfirmation: func</h2><p>参照 <code>&lt;BrowserRouter&gt;</code> 中该属性用法，基本相同。</p>
<h2 id="hashType-string"><a href="#hashType-string" class="headerlink" title="hashType: string"></a>hashType: string</h2><p>设置默认的哈希的编码类型，官方提供三种类型，默认为 <code>&quot;slash&quot;</code> 类型。</p>
<ul>
<li><code>&quot;slash&quot;</code>：URL 显示类似于 <code>http://localhost:3001/home#/test/home</code></li>
<li><code>&quot;noslash&quot;</code>：URL 显示类似于(没有斜杠) <code>http://localhost:3001/home#test/home</code></li>
<li><code>&quot;hashbang&quot;</code>：URL 显示类似于(带感叹号) <code>http://localhost:3001/home#!/test/home</code></li>
</ul>
<p>总体来说，实际应用场景不多，了解即可，需要时请翻阅相关文档。</p>
<h1 id="-2"><a href="#-2" class="headerlink" title=""></a><Link></h1><p><code>&lt;Link&gt;</code> 功能有点类似于 HTML 的 <code>&lt;a&gt;</code> 标签，提供了页面跳转等功能，但是内置了一些属性，功能要比原生的 <code>&lt;a&gt;</code> 标签丰富很多。通过查看源码，也可以发现，<code>&lt;Link&gt;</code> 最终也会被渲染成为 <code>&lt;a&gt;</code> 标签。</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200827211409.gif" alt="&lt;Link&gt; 源码"></p>
<h2 id="to-string"><a href="#to-string" class="headerlink" title="to: string"></a>to: string</h2><p>当该属性为字符串时，表示简单的跳转地址，地址上也可以追加参数。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;Link to&#x3D;&quot;&#x2F;user?name&#x3D;albert&quot;&gt;用户&lt;&#x2F;Link&gt;</span><br></pre></td></tr></table></figure>

<p>当点击了用户时候的跳转，注意看地址栏。</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200827211901.gif" alt="to: string"></p>
<h2 id="to-object"><a href="#to-object" class="headerlink" title="to: object"></a>to: object</h2><p>当该属性为对象时，可以附带四个参数，分别为：</p>
<ul>
<li><code>pathname</code>: 跳转的路径</li>
<li><code>search</code>: 附带的参数</li>
<li><code>hash</code>: 哈希地址</li>
<li><code>state</code>: State to persist to the location.</li>
</ul>
<p>官方案例为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;Link</span><br><span class="line">  to&#x3D;&#123;&#123;</span><br><span class="line">    pathname: &quot;&#x2F;courses&quot;,</span><br><span class="line">    search: &quot;?sort&#x3D;name&quot;,</span><br><span class="line">    hash: &quot;#the-hash&quot;,</span><br><span class="line">    state: &#123; fromDashboard: true &#125;</span><br><span class="line">  &#125;&#125;</span><br><span class="line">&#x2F;&gt;</span><br></pre></td></tr></table></figure>

<p>to: function</p>
<p>该属性还可以设置为函数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;Link to&#x3D;&#123;location &#x3D;&gt; (&#123; ...location, pathname: &quot;&#x2F;courses&quot; &#125;)&#125; &#x2F;&gt;</span><br><span class="line">&lt;Link to&#x3D;&#123;location &#x3D;&gt; &#96;$&#123;location.pathname&#125;?sort&#x3D;name&#96;&#125; &#x2F;&gt;</span><br></pre></td></tr></table></figure>

<h2 id="replace-bool"><a href="#replace-bool" class="headerlink" title="replace: bool"></a>replace: bool</h2><p>该属性可以手动设置为布尔值，也可以单写该属性，不赋值（默认为 <code>true</code>）。当该属性设置为  <code>true</code>，单击链接将替换浏览器历史记录中的链接，而不是添加新的链接到历史记录。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter basename&#x3D;&quot;&#x2F;test&quot; replace &gt;</span><br><span class="line">            &lt;Link to&#x3D;&quot;&#x2F;home&quot; replace&gt;首页&lt;&#x2F;Link&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;Link to&#x3D;&quot;&#x2F;user?name&#x3D;albert&quot; replace&gt;用户&lt;&#x2F;Link&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;Link to&#x3D;&quot;&#x2F;about&quot; replace&gt;关于&lt;&#x2F;Link&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39;&gt;&lt;User&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39;&gt;&lt;About&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;home&#39;&gt;&lt;Home&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p>这里其实是采用了原生 <code>location.replace()</code> 方法。该用法最典型效果是，<code>replace</code> 会在浏览器的浏览历史 <code>History</code> 里面删除当前网址，也就是说，一旦使用了该方法，后退按钮就无法回到当前网页了，相当于在浏览历史里面，使用新的 URL 替换了老的 URL。它的一个应用是，当脚本发现当前是移动设备时，就立刻跳转到移动版网页。</p>
<p>我们尝试把浏览器历史记录清空，然后设置该属性后效果如下：</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829133607.gif" alt="replace 为 true"></p>
<p>此时点击链接跳转后，因为在历史记录里生成链接，所以不能点击返回按钮了。</p>
<h2 id="innerRef-function"><a href="#innerRef-function" class="headerlink" title="innerRef: function"></a>innerRef: function</h2><p>Ref 相关，不常用，后期版本会逐渐废弃，略。</p>
<h2 id="innerRef-RefObject"><a href="#innerRef-RefObject" class="headerlink" title="innerRef: RefObject"></a>innerRef: RefObject</h2><p>Ref 相关，不常用，后期版本会逐渐废弃，略。</p>
<h2 id="component-React-Component"><a href="#component-React-Component" class="headerlink" title="component: React.Component"></a>component: React.Component</h2><p>用于路由中 React 组件嵌套的简写，属性中可以直接配置 React 组件，写法上会简介很多，渲染上无任何差异。</p>
<p>原来写法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">&lt;Switch&gt;</span><br><span class="line">    &lt;Route path&#x3D;&#39;&#x2F;user&#39;&gt;&lt;User&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">    &lt;Route path&#x3D;&#39;&#x2F;about&#39;&gt;&lt;About&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">    &lt;Route path&#x3D;&#39;&#x2F;home&#39;&gt;&lt;Home&#x2F;&gt;&lt;&#x2F;Route&gt;</span><br><span class="line">&lt;&#x2F;Switch&gt;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p>使用该属性后的写法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">&lt;Switch&gt;</span><br><span class="line">    &lt;Route path&#x3D;&#39;&#x2F;user&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">    &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">    &lt;Route path&#x3D;&#39;&#x2F;home&#39; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">&lt;&#x2F;Switch&gt;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<h1 id="-3"><a href="#-3" class="headerlink" title=""></a><NavLink></h1><p>该组件类似于 <code>&lt;Link&gt;</code> ，也是用于链接跳转，但是功能配置比较丰富。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter basename&#x3D;&quot;&#x2F;test&quot;&gt;</span><br><span class="line">            &lt;NavLink to&#x3D;&quot;&#x2F;home&quot; &gt;首页&lt;&#x2F;NavLink&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;NavLink to&#x3D;&quot;&#x2F;user?name&#x3D;albert&quot; &gt;用户&lt;&#x2F;NavLink&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;NavLink to&#x3D;&quot;&#x2F;about&quot; &gt;关于&lt;&#x2F;NavLink&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;home&#39; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p>使用了该组价，页面渲染上跟 <code>&lt;Link&gt;</code> 没有太大区别，但是查看源码会发现 DOM 部分多了几个类名。</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829143459.gif" alt="NavLink 效果"></p>
<p>就拿多出来的这个 <code>active</code> 类，表示选中的标签的状态默认类，如果定义了同类名样式，就会出现选中的样式效果。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">.active &#123;</span><br><span class="line">  background-color: red;</span><br><span class="line">  color: #fff;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829144300.gif" alt="NavLink 设置类样式效果"></p>
<h2 id="activeClassName-string"><a href="#activeClassName-string" class="headerlink" title="activeClassName: string"></a>activeClassName: string</h2><p>该属性可以自定义选中当前元素的类名，用于代替默认的 <code>active</code> 类名。比如尝试自定义了 <code>selected</code> 类名。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">.selected &#123;</span><br><span class="line">  background-color: skyblue;</span><br><span class="line">  color: #fff;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter basename&#x3D;&quot;&#x2F;test&quot;&gt;</span><br><span class="line">            &lt;NavLink to&#x3D;&quot;&#x2F;home&quot; activeClassName&#x3D;&quot;selected&quot;&gt;首页&lt;&#x2F;NavLink&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;NavLink to&#x3D;&quot;&#x2F;user?name&#x3D;albert&quot; activeClassName&#x3D;&quot;selected&quot;&gt;用户&lt;&#x2F;NavLink&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;NavLink to&#x3D;&quot;&#x2F;about&quot; activeClassName&#x3D;&quot;selected&quot;&gt;关于&lt;&#x2F;NavLink&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;home&#39; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829145337.gif" alt="NavLink 自定义类样式效果"></p>
<h2 id="activeStyle-object"><a href="#activeStyle-object" class="headerlink" title="activeStyle: object"></a>activeStyle: object</h2><p>用于设置选中元素的行内样式，采用 JSX 的样式写法。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter basename&#x3D;&quot;&#x2F;test&quot;&gt;</span><br><span class="line">            &lt;NavLink to&#x3D;&quot;&#x2F;home&quot; activeStyle&#x3D;&#123;&#123;</span><br><span class="line">                backgroundColor: &quot;skyblue&quot;,</span><br><span class="line">                color: &quot;red&quot;</span><br><span class="line">            &#125;&#125;&gt;首页&lt;&#x2F;NavLink&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;NavLink to&#x3D;&quot;&#x2F;user?name&#x3D;albert&quot; activeStyle&#x3D;&#123;&#123;</span><br><span class="line">                backgroundColor: &quot;yellow&quot;,</span><br><span class="line">                color: &quot;#2d32ff&quot;</span><br><span class="line">            &#125;&#125;&gt;用户&lt;&#x2F;NavLink&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;NavLink to&#x3D;&quot;&#x2F;about&quot; activeStyle&#x3D;&#123;&#123;</span><br><span class="line">                backgroundColor: &quot;blue&quot;,</span><br><span class="line">                color: &quot;pink&quot;</span><br><span class="line">            &#125;&#125;&gt;关于&lt;&#x2F;NavLink&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;home&#39; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829150436.gif" alt="行内样式效果"></p>
<h2 id="exact-bool"><a href="#exact-bool" class="headerlink" title="exact: bool"></a>exact: bool</h2><p>该属性表示 <code>to=&quot;/home&quot;</code> 路径的一个精准匹配。如果 <code>true</code>，则只有在位置完全匹配时才会触发选中 <code>NavLink</code>。该属性后面的路由匹配加载组件也会用到，用法都差不多。</p>
<p>比如首页现在地址为 <code>http://localhost:3000/test/home</code>。可以尝试访问以下三个链接：</p>
<ul>
<li><code>http://localhost:3000/test/home</code></li>
<li><code>http://localhost:3000/test/home/</code></li>
<li><code>http://localhost:3000/test/home/abc</code></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter basename&#x3D;&quot;&#x2F;test&quot;&gt;</span><br><span class="line">            &lt;NavLink to&#x3D;&quot;&#x2F;home&quot;&gt;首页&lt;&#x2F;NavLink&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;NavLink to&#x3D;&quot;&#x2F;user?name&#x3D;albert&quot;&gt;用户&lt;&#x2F;NavLink&gt;</span><br><span class="line">            &lt;hr&#x2F;&gt;</span><br><span class="line">            &lt;NavLink to&#x3D;&quot;&#x2F;about&quot;&gt;关于&lt;&#x2F;NavLink&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;home&#39; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p>默认没有该属性，或者手动设置为 <code>false</code> 时，这三个路径都可以默认匹配到 <code>to=&quot;/home&quot;</code> ，然后选中该标签。</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829190315.gif" alt="exact false"></p>
<p>如果将该属性设置为 <code>true</code> 后，再次访问该三个链接。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">&lt;NavLink to&#x3D;&quot;&#x2F;home&quot; exact &gt;首页&lt;&#x2F;NavLink&gt;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 或者</span><br><span class="line"></span><br><span class="line">&lt;NavLink to&#x3D;&quot;&#x2F;home&quot; exact&#x3D;&#123;true&#125;&gt;首页&lt;&#x2F;NavLink&gt;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p>可以看到，当开启精准匹配，再次访问 <code>http://localhost:3000/test/home/abc</code> 后，无法匹配 <code>&lt;NavLink to=&quot;/home&quot;&gt;首页&lt;/NavLink&gt;</code> ，该标签不再被选中。</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829191050.gif" alt="exact true"></p>
<h2 id="strict-bool"><a href="#strict-bool" class="headerlink" title="strict: bool"></a>strict: bool</h2><p>该属性表示严格匹配，有些路径末端会有斜杠，比如 <code>&lt;NavLink to=&quot;/home/&quot;&gt;首页&lt;/NavLink&gt;</code>，如果此时该属性设置为 <code>true</code>，<code>&lt;NavLink to=&quot;/home/&quot; strict&gt;首页&lt;/NavLink&gt;</code>。此时只能访问路径中包含 <code>/home/</code> 的 URL，比如 <code>http://localhost:3000/test/home/</code>、<code>http://localhost:3000/test/home/xxx</code> 才会选中该标签，而访问 <code>http://localhost:3000/test/home</code> 是无法匹配的。</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829191834.gif" alt="strict true"></p>
<h2 id="isActive-func"><a href="#isActive-func" class="headerlink" title="isActive: func"></a>isActive: func</h2><h2 id="location-object"><a href="#location-object" class="headerlink" title="location: object"></a>location: object</h2><h2 id="aria-current-string"><a href="#aria-current-string" class="headerlink" title="aria-current: string"></a>aria-current: string</h2><h1 id="-4"><a href="#-4" class="headerlink" title=""></a><MemoryRouter></h1><p>该路由将 URL 的历史记录保存在内存中（不读取或写入地址栏）的。在测试和非浏览器环境（如 React Native）中很有用，详细用法略。</p>
<h1 id="-5"><a href="#-5" class="headerlink" title=""></a><Redirect></h1><p>该组件用于重定向，可以根据条件判断，重定向到相关 URL 地址页面。</p>
<p>例如有这样一个场景，访问一个地址 <code>http://localhost:3000/</code>，如果用户登录，则直接跳转首页，如果没有登录，则直接渲染用户组件，提示未登录。</p>
<p>用户未登录的情况：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">&#x2F;&#x2F;模拟用户登录状态</span><br><span class="line">const loggedIn &#x3D; false;</span><br><span class="line"></span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;home&#39; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&quot;&#x2F;&quot;&gt;&#123;loggedIn ? &lt;Redirect to&#x3D;&quot;&#x2F;home&quot;&#x2F;&gt; : &lt;User&#x2F;&gt;&#125;&lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829211402.gif" alt="用户未登录"></p>
<p>用户已登录的情况：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">&#x2F;&#x2F;模拟用户登录状态</span><br><span class="line">const loggedIn &#x3D; true;</span><br><span class="line"></span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;home&#39; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&quot;&#x2F;&quot;&gt;&#123;loggedIn ? &lt;Redirect to&#x3D;&quot;&#x2F;home&quot;&#x2F;&gt; : &lt;User&#x2F;&gt;&#125;&lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829211612.gif" alt="用户已登录"></p>
<h2 id="to-string-1"><a href="#to-string-1" class="headerlink" title="to: string"></a>to: string</h2><p>改属性为字符串时，用于设置重定向的地址，用法跟之前介绍的 <code>&lt;NavLink&gt;</code> 组件里面的同名属性差不多。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;Redirect to&#x3D;&quot;&#x2F;somewhere&#x2F;else&quot; &#x2F;&gt;</span><br></pre></td></tr></table></figure>

<h2 id="to-object-1"><a href="#to-object-1" class="headerlink" title="to: object"></a>to: object</h2><p>改属性为对象时，可以添加属性，扩展功能。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;Redirect</span><br><span class="line">  to&#x3D;&#123;&#123;</span><br><span class="line">     pathname: &quot;&#x2F;user&quot;, &#x2F;&#x2F;重定向路径</span><br><span class="line">     search: &quot;?name&#x3D;albert&quot;, &#x2F;&#x2F;路径携带参数</span><br><span class="line">     state: &#123;age: &#39;28岁&#39;&#125; &#x2F;&#x2F;通过 this.props.location.state.age 携带年龄数据</span><br><span class="line">  &#125;&#125;</span><br><span class="line">&#x2F;&gt;</span><br></pre></td></tr></table></figure>

<p>例如已经登录的用户，重定向到了 <code>/user</code> 页面。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">&#x2F;&#x2F;模拟用户登录状态</span><br><span class="line">const loggedIn &#x3D; true;</span><br><span class="line"></span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;home&#39; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&quot;&#x2F;&quot;&gt;&#123;loggedIn ? &lt;Redirect</span><br><span class="line">                    to&#x3D;&#123;&#123;</span><br><span class="line">                        pathname: &quot;&#x2F;user&quot;,</span><br><span class="line">                        search: &quot;?name&#x3D;albert&quot;,</span><br><span class="line">                        state: &#123;age: &#39;28岁&#39;&#125;</span><br><span class="line">                    &#125;&#125;</span><br><span class="line">                &#x2F;&gt; : &lt;User&#x2F;&gt;&#125;&lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829212840.gif" alt="to 设置为对象"></p>
<p>通过浏览器的 React 开发插件，也可以看到相关数据。这里的 <code>props.location、props.match</code>后面会提到，会存储一些关键信息。</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829213125.gif" alt="查看相关参数"></p>
<h2 id="push-bool"><a href="#push-bool" class="headerlink" title="push: bool"></a>push: bool</h2><p>默认页面重定向操作，是不会在浏览器的历史记录里面生成记录的，类似于 <code>location.replace()</code> 效果，但是可以通过设置该属性为 <code>true</code> ，在历史记录里面添加记录。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;Redirect push to&#x3D;&quot;&#x2F;user&quot; &#x2F;&gt;</span><br></pre></td></tr></table></figure>

<h2 id="from-string"><a href="#from-string" class="headerlink" title="from: string"></a>from: string</h2><p>该属性表示，从哪里来的链接需要重定向，限定了页面的来源。比如某个项目废弃了 <code>/old-path</code> 页面的项目，需要全部更新为 <code>/new-path</code> 项目，就可以这样使用。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Redirect from&#x3D;&#39;&#x2F;old-path&#39; to&#x3D;&#39;&#x2F;new-path&#39;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;new-path&#39; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829215209.gif" alt="限定页面来源的重定向"></p>
<h2 id="exact-bool-1"><a href="#exact-bool-1" class="headerlink" title="exact: bool"></a>exact: bool</h2><p>用于精准匹配，基本和之前提到的同名属性用法相同。用在重定向组件里有一点要注意点的是，该属性必须配合和 <code>from</code> 属性一起用才能呈现效果。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Redirect exact from&#x3D;&quot;&#x2F;&quot; to&#x3D;&quot;&#x2F;home&quot;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&quot;&#x2F;home&quot;&gt;</span><br><span class="line">                    &lt;Home&#x2F;&gt;</span><br><span class="line">                &lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&quot;&#x2F;about&quot;&gt;</span><br><span class="line">                    &lt;About&#x2F;&gt;</span><br><span class="line">                &lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<h2 id="strict-bool-1"><a href="#strict-bool-1" class="headerlink" title="strict: bool"></a>strict: bool</h2><p>用于严格匹配，基本和之前提到的同名属性用法相同。用在重定向组件里有一点要注意点的是，该属性必须配合和 <code>from</code> 属性一起用才能呈现效果。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Redirect strict from&#x3D;&quot;&#x2F;old&#x2F;&quot; to&#x3D;&quot;&#x2F;home&quot;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&quot;&#x2F;home&quot;&gt;</span><br><span class="line">                    &lt;Home&#x2F;&gt;</span><br><span class="line">                &lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&quot;&#x2F;about&quot;&gt;</span><br><span class="line">                    &lt;About&#x2F;&gt;</span><br><span class="line">                &lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<h2 id="sensitive-bool"><a href="#sensitive-bool" class="headerlink" title="sensitive: bool"></a>sensitive: bool</h2><p>表示是否匹配大小写，设置为 <code>true</code> ，表示匹配大小写。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Redirect sensitive from&#x3D;&quot;&#x2F;old&#x2F;&quot; to&#x3D;&quot;&#x2F;home&quot;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&quot;&#x2F;home&quot;&gt;</span><br><span class="line">                    &lt;Home&#x2F;&gt;</span><br><span class="line">                &lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&quot;&#x2F;about&quot;&gt;</span><br><span class="line">                    &lt;About&#x2F;&gt;</span><br><span class="line">                &lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此时，URL 上访问 <code>/old</code> 和 <code>/OLD</code> 是有区别的。</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829222248.gif" alt="区分大小写"></p>
<h1 id="-6"><a href="#-6" class="headerlink" title=""></a><Route></h1><p><code>&lt;Route&gt;</code> 可以说是 React Router 中最重要的组件了。到目前为止，之前的所有案例，基本都用到了该组件。它最基本的功能是在其路径与当前 URL 匹配时渲染组件，呈现页面 UI。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;div&gt;</span><br><span class="line">                &lt;Route exact path&#x3D;&quot;&#x2F;&quot;&gt;</span><br><span class="line">                    &lt;Home&#x2F;&gt;</span><br><span class="line">                &lt;&#x2F;Route&gt;</span><br><span class="line">                &lt;Route path&#x3D;&quot;&#x2F;about&quot;&gt;</span><br><span class="line">                    &lt;About&#x2F;&gt;</span><br><span class="line">                &lt;&#x2F;Route&gt;</span><br><span class="line">            &lt;&#x2F;div&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;)</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200829225817.gif" alt="Route 路径匹配"></p>
<h2 id="Route-render-methods"><a href="#Route-render-methods" class="headerlink" title="Route render methods"></a>Route render methods</h2><p><code>&lt;Route&gt;</code> 匹配 URL 渲染组件有三种方式，推荐使用 <code>component</code> 方式。</p>
<ul>
<li><code>&lt;Route component&gt;</code></li>
<li><code>&lt;Route render&gt;</code></li>
<li><code>&lt;Route children&gt; function</code></li>
</ul>
<h2 id="Route-props"><a href="#Route-props" class="headerlink" title="Route props"></a>Route props</h2><p><code>&lt;Route&gt;</code></p>
<h2 id="component"><a href="#component" class="headerlink" title="component"></a>component</h2><h2 id="render-func"><a href="#render-func" class="headerlink" title="render: func"></a>render: func</h2><h2 id="children-func"><a href="#children-func" class="headerlink" title="children: func"></a>children: func</h2><h2 id="path-string-string"><a href="#path-string-string" class="headerlink" title="path: string | string[]"></a>path: string | string[]</h2><p>路由匹配的路径，可以为字符串，或者数组。</p>
<h3 id="path-string"><a href="#path-string" class="headerlink" title="path: string"></a>path: string</h3><p>当属性为单条字符串时，表示单个路径匹配。例如，这里需要匹配 <code>/user</code> 地址，渲染用户组件。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">import React from &quot;react&quot;;</span><br><span class="line">import &#123;BrowserRouter, Route, Switch&#125; from &quot;react-router-dom&quot;;</span><br><span class="line"></span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#x2F;:id&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function User(props) &#123;</span><br><span class="line">    return &lt;div&gt;用户编号：&#123;props.match.params.id&#125;&lt;&#x2F;div&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">export default App;</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200831171035.gif" alt="单条匹配"></p>
<h3 id="path-string-1"><a href="#path-string-1" class="headerlink" title="path: string[]"></a>path: string[]</h3><p>当属性为数组字符串时，表示多个路径匹配。例如，这里可以同时匹配 <code>&#39;/user/:id&#39;,&#39;/abc/:id&#39;</code> 两个地址地址，渲染用户组件。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">import React from &quot;react&quot;;</span><br><span class="line">import &#123;BrowserRouter, Route, Switch&#125; from &quot;react-router-dom&quot;;</span><br><span class="line"></span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#123;[&#39;&#x2F;user&#x2F;:id&#39;,&#39;&#x2F;abc&#x2F;:id&#39;]&#125; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function User(props) &#123;</span><br><span class="line">    return &lt;div&gt;用户编号：&#123;props.match.params.id&#125;&lt;&#x2F;div&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">export default App;</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200831172202.gif" alt="多条匹配"></p>
<p>注意：如果不设置 <code>path</code> ，表示路径总是匹配，随便输入什么都可以匹配。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">&lt;Switch&gt;</span><br><span class="line">    &lt;Route component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">&lt;&#x2F;Switch&gt;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200831201414.gif" alt="不设置 path"></p>
<h2 id="exact-bool-2"><a href="#exact-bool-2" class="headerlink" title="exact: bool"></a>exact: bool</h2><p>表示精准匹配，当为 <code>true</code> 时，只有当路径与 <code>location.path</code> 名称完全匹配时，才会匹配路由，渲染组件。</p>
<p>这个属性会出现在 React Router 的很多组件上，用法基本相同。官方的这个表格阐述的很清楚，可以做参考。</p>
<table>
<thead>
<tr>
<th>path</th>
<th>location.pathname</th>
<th>exact</th>
<th>matches?</th>
</tr>
</thead>
<tbody><tr>
<td>/one</td>
<td>/one/two</td>
<td>true</td>
<td>no</td>
</tr>
<tr>
<td>/one</td>
<td>/one/two</td>
<td>false</td>
<td>yes</td>
</tr>
</tbody></table>
<h2 id="strict-bool-2"><a href="#strict-bool-2" class="headerlink" title="strict: bool"></a>strict: bool</h2><p>如果为 <code>true</code>，则具有尾斜杠的路径将只匹配 <code>location.path</code> 名称和尾斜杠。当 <code>location.path</code> 名称中有额外的 URL 时，这没有任何影响。</p>
<p>这个属性会出现在 React Router 的很多组件上，用法基本相同。官方的这个表格阐述的很清楚，可以做参考。</p>
<table>
<thead>
<tr>
<th>path</th>
<th>location.pathname</th>
<th>strict</th>
<th>matches?</th>
</tr>
</thead>
<tbody><tr>
<td>/one/</td>
<td>/one</td>
<td>true</td>
<td>no</td>
</tr>
<tr>
<td>/one/</td>
<td>/one/</td>
<td>true</td>
<td>yes</td>
</tr>
<tr>
<td>/one/</td>
<td>/one/two</td>
<td>true</td>
<td>yes</td>
</tr>
</tbody></table>
<p><code>strict</code> 也可以和 <code>exact</code> 同时使用，用来强制限制一个没有尾斜杠路径。</p>
<table>
<thead>
<tr>
<th>path</th>
<th>location.pathname</th>
<th>exact</th>
<th>strict</th>
<th>matches?</th>
</tr>
</thead>
<tbody><tr>
<td>/one/</td>
<td>/one</td>
<td>true</td>
<td>true</td>
<td>yes</td>
</tr>
<tr>
<td>/one/</td>
<td>/one/</td>
<td>true</td>
<td>true</td>
<td>no</td>
</tr>
<tr>
<td>/one/</td>
<td>/one/two</td>
<td>true</td>
<td>true</td>
<td>no</td>
</tr>
</tbody></table>
<h2 id="location-object-1"><a href="#location-object-1" class="headerlink" title="location: object"></a>location: object</h2><p>一会儿看</p>
<h2 id="sensitive-bool-1"><a href="#sensitive-bool-1" class="headerlink" title="sensitive: bool"></a>sensitive: bool</h2><p>为 <code>true</code> 时，表示路径匹配是否区分大小写。</p>
<table>
<thead>
<tr>
<th>path</th>
<th>location.pathname</th>
<th>sensitive</th>
<th>matches?</th>
</tr>
</thead>
<tbody><tr>
<td>/one</td>
<td>/one</td>
<td>true</td>
<td>yes</td>
</tr>
<tr>
<td>/One</td>
<td>/one</td>
<td>true</td>
<td>no</td>
</tr>
<tr>
<td>/One</td>
<td>/one</td>
<td>false</td>
<td>yes</td>
</tr>
</tbody></table>
<h1 id="-7"><a href="#-7" class="headerlink" title=""></a><Router></h1><p>官方对 <code>&lt;Router&gt;</code> 的解释为低级的组件，实际工作中用到的不多，不做详细阐述。推荐用以下高级的组件：</p>
<ul>
<li><code>&lt;BrowserRouter&gt;</code></li>
<li><code>&lt;HashRouter&gt;</code></li>
<li><code>&lt;MemoryRouter&gt;</code></li>
<li><code>&lt;NativeRouter&gt;</code></li>
<li><code>&lt;StaticRouter&gt;</code></li>
</ul>
<h1 id="-8"><a href="#-8" class="headerlink" title=""></a><StaticRouter></h1><p>官方定义为不改变位置的路由。</p>
<p>怎么理解这个定义呢？之前的所有案例基于环境都是浏览器，都是在浏览器地址栏展示路由切换效果。这个组件是用在服务器端的。不存在用户的点击切换，所以位置不变。所以，这个路由名字是：静态的。</p>
<p>官方使用 <code>nodejs</code>，进行了一个简单的后台服务器开发，前端请求，服务器端返回地址的案例。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">import http from &quot;http&quot;;</span><br><span class="line">import React from &quot;react&quot;;</span><br><span class="line">import ReactDOMServer from &quot;react-dom&#x2F;server&quot;;</span><br><span class="line">import &#123; StaticRouter &#125; from &quot;react-router&quot;;</span><br><span class="line"></span><br><span class="line">http</span><br><span class="line">  .createServer((req, res) &#x3D;&gt; &#123;</span><br><span class="line">    &#x2F;&#x2F; This context object contains the results of the render</span><br><span class="line">    const context &#x3D; &#123;&#125;;</span><br><span class="line"></span><br><span class="line">    const html &#x3D; ReactDOMServer.renderToString(</span><br><span class="line">      &lt;StaticRouter location&#x3D;&#123;req.url&#125; context&#x3D;&#123;context&#125;&gt;</span><br><span class="line">        &lt;App &#x2F;&gt;</span><br><span class="line">      &lt;&#x2F;StaticRouter&gt;</span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; context.url will contain the URL to redirect to if a &lt;Redirect&gt; was used</span><br><span class="line">    if (context.url) &#123;</span><br><span class="line">      res.writeHead(302, &#123;</span><br><span class="line">        Location: context.url</span><br><span class="line">      &#125;);</span><br><span class="line">      res.end();</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">      res.write(html);</span><br><span class="line">      res.end();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">  .listen(3000);</span><br></pre></td></tr></table></figure>

<h2 id="basename-string-2"><a href="#basename-string-2" class="headerlink" title="basename: string"></a>basename: string</h2><p>跟之前介绍 <code>&lt;/BrowserRouter&gt;</code> 组件的<a href="#basename">同名属性</a>功能相同。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;StaticRouter basename&#x3D;&quot;&#x2F;calendar&quot;&gt;</span><br><span class="line">  &lt;Link to&#x3D;&quot;&#x2F;today&quot;&#x2F;&gt; &#x2F;&#x2F; renders &lt;a href&#x3D;&quot;&#x2F;calendar&#x2F;today&quot;&gt;</span><br><span class="line">&lt;&#x2F;StaticRouter&gt;</span><br></pre></td></tr></table></figure>

<h2 id="location-string"><a href="#location-string" class="headerlink" title="location: string"></a>location: string</h2><p>服务器端返回的 URL。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;StaticRouter location&#x3D;&#123;req.url&#125;&gt;</span><br><span class="line">  &lt;App &#x2F;&gt;</span><br><span class="line">&lt;&#x2F;StaticRouter&gt;</span><br></pre></td></tr></table></figure>

<h2 id="location-object-2"><a href="#location-object-2" class="headerlink" title="location: object"></a>location: object</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;StaticRouter location&#x3D;&#123;&#123; pathname: &quot;&#x2F;bubblegum&quot; &#125;&#125;&gt;</span><br><span class="line">  &lt;App &#x2F;&gt;</span><br><span class="line">&lt;&#x2F;StaticRouter&gt;</span><br></pre></td></tr></table></figure>

<h2 id="context-object"><a href="#context-object" class="headerlink" title="context: object"></a>context: object</h2><p>一个普通的JavaScript对象。在呈现过程中，组件可以向对象添加属性以存储有关呈现的信息。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">const context &#x3D; &#123;&#125;</span><br><span class="line">&lt;StaticRouter context&#x3D;&#123;context&#125;&gt;</span><br><span class="line">  &lt;App &#x2F;&gt;</span><br><span class="line">&lt;&#x2F;StaticRouter&gt;</span><br></pre></td></tr></table></figure>

<p>当一个路由&gt;；匹配时，它将把上下文对象传递给它作为静态上下文支柱呈现的组件。有关如何自己完成此操作的更多信息，请参阅服务器呈现指南。</p>
<p>在呈现之后，可以使用这些属性配置服务器的响应。</p>
<h2 id="children-node"><a href="#children-node" class="headerlink" title="children: node"></a>children: node</h2><h1 id="-9"><a href="#-9" class="headerlink" title=""></a><Switch></h1><p>用于匹配第一个符合路径条件的 <code>&lt;Route&gt;</code> 或 <code>&lt;Redirect&gt;</code>。</p>
<h2 id="使用-与不使用的区别"><a href="#使用-与不使用的区别" class="headerlink" title="使用  与不使用的区别"></a>使用 <Switch> 与不使用的区别</h2><p><code>&lt;Switch&gt;</code> 是唯一的，因为它只呈现一个路由。相反，不使用它的话，匹配位置的每一个路由都具有包容性。考虑以下几种情况：</p>
<h3 id="不使用-lt-Switch-gt-："><a href="#不使用-lt-Switch-gt-：" class="headerlink" title="不使用 &lt;Switch&gt;："></a>不使用 <code>&lt;Switch&gt;</code>：</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Route path&#x3D;&#39;&#x2F;&#39; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">            &lt;Route path&#x3D;&#39;&#x2F;user&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">            &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200903142119.gif" alt="不使用 `&lt;Switch&gt;`"></p>
<p>在不使 <code>&lt;Switch&gt;</code> 的情况下，为什么无论 URL 如何变化，永远都会显示首页组件呢？因为路由的匹配是从上到下的，而不使用 <code>&lt;Switch&gt;</code>的情况下，会多路由匹配。这样一来，无论访问 <code>/user</code> 还是 <code>/about</code>，都会匹配 <code>/</code> ，从而显示首页组件。</p>
<h3 id="使用-lt-Switch-gt-："><a href="#使用-lt-Switch-gt-：" class="headerlink" title="使用 &lt;Switch&gt;："></a>使用 <code>&lt;Switch&gt;</code>：</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;&#39; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200903143126.gif" alt="使用 `&lt;Switch&gt;`"></p>
<p>使用了 <code>&lt;Switch&gt;</code> 的情况下，为什么无论 URL 如何变化，永远都只会显示首页组件呢？因为路由的匹配是从上到下的，使用 <code>&lt;Switch&gt;</code>的情况下，会单一路由匹配。这样一来，无论访问 <code>/user</code> 还是 <code>/about</code>，都会匹配 <code>/</code> ，渲染第一个组件，从而只显示首页组件。</p>
<p>通常情况下，这种首页的 <code>/</code> 根地址的路由，会放在最底部，或者添加 <code>exact</code> 属性，精准匹配，从而避免类似问题。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route exact path&#x3D;&#39;&#x2F;&#39; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200903153717.gif" alt="优化效果"></p>
<h2 id="location-object-3"><a href="#location-object-3" class="headerlink" title="location: object"></a>location: object</h2><h2 id="children-node-1"><a href="#children-node-1" class="headerlink" title="children: node"></a>children: node</h2><p><code>&lt;Switch&gt;</code> 的所有子元素都应该是 <code>&lt;Route&gt;</code> 或者 <code>&lt;Redirect&gt;</code> 元素组件，匹配第一个与当前 URL 符合的组件。</p>
<p><code>&lt;Route&gt;</code> 使用其路径(<code>path</code>)进行匹配，而 <code>&lt;Redirect&gt;</code> 使用它的来源路径(<code>from</code>)进行匹配。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;&#39; exact component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Redirect from&#x3D;&quot;&#x2F;olduser&quot; to&#x3D;&quot;&#x2F;user&quot;&#x2F;&gt;</span><br><span class="line">                &lt;Redirect from&#x3D;&quot;&#x2F;oldabout&quot; to&#x3D;&quot;&#x2F;about&quot;&#x2F;&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200903162407.gif" alt="children: node 效果"></p>
<p>如果 <code>&lt;Route&gt;</code> 没有 <code>path</code> 属性， 或者 <code>&lt;Redirect&gt;</code> 没有 <code>from</code> 属性，则总是匹配第一个组件。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">function App() &#123;</span><br><span class="line">    return (</span><br><span class="line">        &lt;BrowserRouter&gt;</span><br><span class="line">            &lt;Switch&gt;</span><br><span class="line">                &lt;Route exact component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;user&#39; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Route path&#x3D;&#39;&#x2F;about&#39; component&#x3D;&#123;About&#125;&#x2F;&gt;</span><br><span class="line">                &lt;Redirect to&#x3D;&quot;&#x2F;user&quot;&#x2F;&gt;</span><br><span class="line">                &lt;Redirect to&#x3D;&quot;&#x2F;about&quot;&#x2F;&gt;</span><br><span class="line">            &lt;&#x2F;Switch&gt;</span><br><span class="line">        &lt;&#x2F;BrowserRouter&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200903162544.gif" alt="无路径"></p>
<h1 id="history"><a href="#history" class="headerlink" title="history"></a>history</h1><p>history is mutable</p>
<h1 id="location"><a href="#location" class="headerlink" title="location"></a>location</h1><h1 id="match"><a href="#match" class="headerlink" title="match"></a>match</h1><p>null matches</p>
<h1 id="matchPath"><a href="#matchPath" class="headerlink" title="matchPath"></a>matchPath</h1><p>pathname<br>props<br>returns</p>
<h1 id="withRouter"><a href="#withRouter" class="headerlink" title="withRouter"></a>withRouter</h1><p>Component.WrappedComponent<br>wrappedComponentRef: func</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/08/03/%E9%83%A8%E5%88%86%E5%8C%BA%E5%9F%9F%E6%87%92%E5%8A%A0%E8%BD%BD%E6%A1%88%E4%BE%8B/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://inews.gtimg.com/newsapp_ls/0/12122532695/0">
      <meta itemprop="name" content="Albert Guo">
      <meta itemprop="description" content="郭鹏松的个人博客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Albert Guo">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2020/08/03/%E9%83%A8%E5%88%86%E5%8C%BA%E5%9F%9F%E6%87%92%E5%8A%A0%E8%BD%BD%E6%A1%88%E4%BE%8B/" class="post-title-link" itemprop="url">部分区域懒加载案例</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-08-03 19:02:31" itemprop="dateCreated datePublished" datetime="2020-08-03T19:02:31+08:00">2020-08-03</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-08-23 22:23:40" itemprop="dateModified" datetime="2020-08-23T22:23:40+08:00">2020-08-23</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="需求描述"><a href="#需求描述" class="headerlink" title="需求描述"></a>需求描述</h1><p>最近接到一个需求，需要实现在页面的部分区域，实现上拉加载，下拉加载等类似的需求。而且第一次滑倒末端，不加载，只有第二次尝试滑动才加载切换导航。</p>
<p>之前做个类似需求，但是都是整屏幕的，这回不同的是部分区域。</p>
<h1 id="布局解析"><a href="#布局解析" class="headerlink" title="布局解析"></a>布局解析</h1><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200823155910.png" width = "375" height = "1008" alt="布局解析" align="center">

<p>效果如下：</p>
<img src="https://gitee.com/guopengsong1/image-url/raw/master/20200823205313.gif" width = "375" height = "667" alt="布局解析" align="left">

<h1 id="实现思路"><a href="#实现思路" class="headerlink" title="实现思路"></a>实现思路</h1><p>需求的难点：</p>
<ol>
<li>如何判断内容区域滑到弹出框（阅读滑动区域）了顶端/末端？</li>
<li>如何仅在第二次滑动触发回调动作？</li>
</ol>
<p>对于第一个问题，其实按照示例图的分割，可以尝试得到一个判断公式。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 何时滑动到最顶端？</span><br><span class="line"></span><br><span class="line">内容区域滑动到最顶端 &#x3D; 内容区域距离可视区域顶部距离 &gt;&#x3D; 可视区域高度 - 阅读滑动区域高度</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 何时滑动到最底端？</span><br><span class="line"></span><br><span class="line">内容区域滑动到最底端 &#x3D; 内容区域距离可视区域顶部距离 &gt;&#x3D; 内容区域高度 - 可视区域高度</span><br></pre></td></tr></table></figure>

<p>然后通过监听滑动区域的滚动操作，实时获取元素的 <code>y</code> 坐标， <code>element.getBoundingClientRect().y</code> 。</p>
<p>对于第二个问题，可以采用一个中间量，去缓存自增，但是需要记住，每一次切换，需要归位。</p>
<h1 id="核心代码"><a href="#核心代码" class="headerlink" title="核心代码"></a>核心代码</h1><p>滚动检测：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;检测权益是否滑动到顶部，底部</span><br><span class="line">   TOOL_quanYiXiangQingHuaDong &#x3D; () &#x3D;&gt; &#123;</span><br><span class="line">       let DOM_1 &#x3D; document.documentElement;&#x2F;&#x2F;页面可视区域</span><br><span class="line">       let DOM_2 &#x3D; document.getElementById(&#39;quanYiXiangQing1&#39;);&#x2F;&#x2F;权益壳子元素</span><br><span class="line">       let DOM_3 &#x3D; document.getElementById(&#39;quanYiXiangQing2&#39;);&#x2F;&#x2F;权益内容元素</span><br><span class="line"></span><br><span class="line">       let DOM_1H &#x3D; 0;&#x2F;&#x2F;页面可视区域高度</span><br><span class="line">       let DOM_2H &#x3D; 0;&#x2F;&#x2F;权益壳子元素高度</span><br><span class="line">       let DOM_3H &#x3D; 0;&#x2F;&#x2F;权益内容元素</span><br><span class="line"></span><br><span class="line">       let topH &#x3D; 0;&#x2F;&#x2F;权益内容元素距离屏幕顶部距离</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">       let that &#x3D; this;</span><br><span class="line">       if (DOM_1 &amp;&amp; DOM_2 &amp;&amp; DOM_3) &#123;</span><br><span class="line">           DOM_1H &#x3D; DOM_1.clientHeight;</span><br><span class="line">           DOM_2H &#x3D; DOM_2.clientHeight;</span><br><span class="line">           DOM_3H &#x3D; DOM_3.clientHeight;</span><br><span class="line">           DOM_2.onscroll &#x3D; function () &#123;</span><br><span class="line">               topH &#x3D; DOM_3.getBoundingClientRect().y;</span><br><span class="line">               let a &#x3D; Math.abs(DOM_1H - DOM_2H);</span><br><span class="line">               let b &#x3D; Math.abs(DOM_3H - DOM_1H) - 1;</span><br><span class="line">               let upNum &#x3D; that.upNum;&#x2F;&#x2F;权益详情上下滑动标识</span><br><span class="line">               let downNum &#x3D; that.downNum;&#x2F;&#x2F;权益详情下滑动标识</span><br><span class="line">               if (topH &gt;&#x3D; a) &#123;</span><br><span class="line">                   &#x2F;&#x2F; console.log(&#39;到-顶部-了&#39;);</span><br><span class="line">                   upNum +&#x3D; 1;</span><br><span class="line">                   that.upNum &#x3D; upNum;</span><br><span class="line">                   if (upNum &#x3D;&#x3D; 2) &#123;</span><br><span class="line">                       that.upNum &#x3D; 0;</span><br><span class="line">                       console.log(&#39;该切换上一个了&#39;);</span><br><span class="line">                       that.FN_qieHuanBiaoQian(true)</span><br><span class="line">                   &#125;</span><br><span class="line">               &#125;</span><br><span class="line"></span><br><span class="line">               if (Math.abs(topH) &gt;&#x3D; b) &#123;</span><br><span class="line">                   &#x2F;&#x2F; console.log(&#39;到-底部-了&#39;);</span><br><span class="line">                   downNum +&#x3D; 1;</span><br><span class="line">                   that.downNum &#x3D; downNum;</span><br><span class="line">                   if (downNum &#x3D;&#x3D; 2) &#123;</span><br><span class="line">                       that.downNum &#x3D; 0;</span><br><span class="line">                       console.log(&#39;该切换下一个了&#39;);</span><br><span class="line">                       that.FN_qieHuanBiaoQian(false)</span><br><span class="line">                   &#125;</span><br><span class="line">               &#125;</span><br><span class="line"></span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;;</span><br></pre></td></tr></table></figure>

<p>二次滑动切换：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;滑动二次切换</span><br><span class="line">   FN_qieHuanBiaoQian &#x3D; (flag) &#x3D;&gt; &#123;</span><br><span class="line">       let processData &#x3D; this.state.processData;</span><br><span class="line">       let processIndex &#x3D; this.state.processIndex;</span><br><span class="line">       let arr &#x3D; [];</span><br><span class="line">       if (processData &amp;&amp; processData.length &gt; 0) &#123;</span><br><span class="line">           processData.forEach(function (v, i) &#123;</span><br><span class="line">               if (v.dataList &amp;&amp; v.dataList.length &gt; 0) &#123;</span><br><span class="line">                   arr.push(i)</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;)</span><br><span class="line">       &#125;</span><br><span class="line">       let nowI &#x3D; arr.findIndex(function (v, i) &#123;</span><br><span class="line">           return v &#x3D;&#x3D;&#x3D; processIndex;</span><br><span class="line">       &#125;);</span><br><span class="line"></span><br><span class="line">       let next &#x3D; processIndex;</span><br><span class="line">       if (nowI &#x3D;&#x3D;&#x3D; 0) &#123;</span><br><span class="line">           next &#x3D; flag ? arr[nowI] : arr[nowI + 1];</span><br><span class="line">       &#125; else if (nowI &#x3D;&#x3D;&#x3D; arr.length - 1) &#123;</span><br><span class="line">           next &#x3D; flag ? arr[nowI - 1] : arr[nowI];</span><br><span class="line">       &#125; else &#123;</span><br><span class="line">           next &#x3D; flag ? arr[nowI - 1] : arr[nowI + 1];</span><br><span class="line">       &#125;</span><br><span class="line">       this.setState(&#123;</span><br><span class="line">           processIndex: next</span><br><span class="line">       &#125;, () &#x3D;&gt; &#123;</span><br><span class="line">           &#x2F;&#x2F; this.upNum&#x3D;0;&#x2F;&#x2F;权益详情上下滑动标识</span><br><span class="line">           &#x2F;&#x2F; this.downNum&#x3D;0;&#x2F;&#x2F;权益详情下滑动标识</span><br><span class="line"></span><br><span class="line">           this.TOOL_quanYiXiangQingHuaDong()</span><br><span class="line">       &#125;)</span><br><span class="line">   &#125;;</span><br></pre></td></tr></table></figure>
      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/06/28/%E5%B7%A7%E7%94%A8-Swiper-%E5%AE%9E%E7%8E%B0%E5%8F%A6%E7%B1%BB%E5%B8%83%E5%B1%80%E8%BD%AE%E6%92%AD%E5%9B%BE/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://inews.gtimg.com/newsapp_ls/0/12122532695/0">
      <meta itemprop="name" content="Albert Guo">
      <meta itemprop="description" content="郭鹏松的个人博客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Albert Guo">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2020/06/28/%E5%B7%A7%E7%94%A8-Swiper-%E5%AE%9E%E7%8E%B0%E5%8F%A6%E7%B1%BB%E5%B8%83%E5%B1%80%E8%BD%AE%E6%92%AD%E5%9B%BE/" class="post-title-link" itemprop="url">巧用 Swiper 实现另类布局轮播图</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-06-28 17:37:47" itemprop="dateCreated datePublished" datetime="2020-06-28T17:37:47+08:00">2020-06-28</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-08-23 22:24:32" itemprop="dateModified" datetime="2020-08-23T22:24:32+08:00">2020-08-23</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>最近接到产品一个需求，需要仿照支付宝的理财的一个轮播图，做一个类似的效果。</p>
<p>我打开了支付宝理财界面的轮播图效果如下：</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200823205552.jpeg" alt="支付宝理财轮播图"></p>
<p>分析过后，这个轮播图的特殊之处在于：</p>
<ul>
<li>第一张轮播图时候，左侧不展示内容，右侧漏出第二张轮播图，左右不对称；</li>
<li>最后一张轮播的时候，右侧不展示内容，左侧漏出倒数第二张轮播图，左右不对称；</li>
<li>切换到非收尾的时候，轮播图左右漏出其他图，此时左右对称；</li>
<li>切换流畅，每次滑动切换单张。</li>
</ul>
<p>目前找了几种主流的轮播图插件，功能最强大的要数第三方的 Swiper 了，而且拓展方法比较全，但是也很难实现这种布局的轮播。</p>
<p>尝试了修改插件默认样式，但是渲染时会被覆盖，而且污染原有DOM样式，效果不理想。又从 Swiper 官方声明周期入手，尝试用 JavaScript 改写行内样式，但是效果也不理想。</p>
<p>自己重新写插件的话，时间来不及，而且很难写出 Swiper 这样功能丰富好用的插件了。</p>
<p>于是研究了官方文档，发现有几个参数，可以实现这种方式。但是需要 Swiper5 版本的支持。</p>
<p><img src="https://inews.gtimg.com/newsapp_ls/0/12087687501/0" alt="Swiper 版本支持"></p>
<p>于是，对项目的 package.json 文件中 Swiper 进行了升级，然后相关参数设置如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">this.swiper &#x3D; new Swiper(&#39;.study-swiper&#39;, &#123;</span><br><span class="line">          slidesPerView: 1.1,&#x2F;&#x2F;设置slider容器能够同时显示的slides数量(carousel模式)。</span><br><span class="line">          spaceBetween: 10,&#x2F;&#x2F;在slide之间设置距离（单位px）。</span><br><span class="line">          direction: &#39;horizontal&#39;,</span><br><span class="line">          loop: false,</span><br><span class="line">          centeredSlides: true,</span><br><span class="line">          centeredSlidesBounds: true,&#x2F;&#x2F;开启这个参数，当slides的总数小于slidesPerView时，slides居中。</span><br><span class="line">          initialSlide: 0,</span><br><span class="line">          on: &#123;</span><br><span class="line">              fromEdge: function () &#123;</span><br><span class="line">                  _this.setState(&#123; curIndex: this.realIndex &#125;, () &#x3D;&gt; &#123;</span><br><span class="line">                      _this.navScroll()</span><br><span class="line">                  &#125;)</span><br><span class="line">              &#125;,</span><br><span class="line">              slideChange: function () &#123;</span><br><span class="line">                  _this.setState(&#123; curIndex: this.realIndex &#125;, () &#x3D;&gt; &#123;</span><br><span class="line">                      _this.navScroll()</span><br><span class="line">                  &#125;)</span><br><span class="line">              &#125;,</span><br><span class="line">              reachBeginning: function () &#123;</span><br><span class="line">                  _this.setState(&#123; curIndex: 0 &#125;, () &#x3D;&gt; &#123;</span><br><span class="line">                      _this.navScroll()</span><br><span class="line">                  &#125;)</span><br><span class="line">              &#125;,</span><br><span class="line">              reachEnd: function () &#123;</span><br><span class="line">                  _this.setState(&#123; curIndex: _this.state.cardList.length - 1 &#125;, () &#x3D;&gt; &#123;</span><br><span class="line">                      _this.navScroll()</span><br><span class="line">                  &#125;)</span><br><span class="line">              &#125;</span><br><span class="line">          &#125;,</span><br><span class="line">      &#125;)</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>官方的参数这设置完成后，其实有个 bug，就是点击索引跳转后，对不上，比如点了话题pk，此时应该去第一张图，但是因为第一张图里面还有第二张的内容，所以会发生错位，此时需要手动获取索引改写DOM，解决该 bug。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">navScroll &#x3D; () &#x3D;&gt; &#123;</span><br><span class="line">    let navScrollEle &#x3D; document.querySelector(&#39;.topicEntry__nav__wrap&#39;),</span><br><span class="line">        navItemDoms &#x3D; document.querySelectorAll(&#39;.topicEntry__nav__inner span&#39;),</span><br><span class="line">        &#123; curIndex &#125; &#x3D; this.state,</span><br><span class="line">        targetDom &#x3D; navItemDoms[curIndex]</span><br><span class="line">        </span><br><span class="line">    if (!targetDom) return;</span><br><span class="line"></span><br><span class="line">    let xDis &#x3D; targetDom.offsetLeft,</span><br><span class="line">        targetWth &#x3D; targetDom.getBoundingClientRect().width,</span><br><span class="line">        winWth &#x3D; window.innerWidth </span><br><span class="line">navScrollEle.scroll(xDis + targetWth &#x2F; 2 - winWth &#x2F; 2, 0)</span><br></pre></td></tr></table></figure>

<p>最终完美实现的效果图：</p>
<p><img src="https://gitee.com/guopengsong1/image-url/raw/master/20200823205518.gif" alt="效果图"></p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/05/14/%E6%B5%85%E8%B0%88SplitChunksPlugin/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://inews.gtimg.com/newsapp_ls/0/12122532695/0">
      <meta itemprop="name" content="Albert Guo">
      <meta itemprop="description" content="郭鹏松的个人博客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Albert Guo">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2020/05/14/%E6%B5%85%E8%B0%88SplitChunksPlugin/" class="post-title-link" itemprop="url">浅谈SplitChunksPlugin</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-05-14 16:27:15" itemprop="dateCreated datePublished" datetime="2020-05-14T16:27:15+08:00">2020-05-14</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-07 20:01:12" itemprop="dateModified" datetime="2020-07-07T20:01:12+08:00">2020-07-07</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/webpack/" itemprop="url" rel="index"><span itemprop="name">webpack</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="SplitChunksPlugin"><a href="#SplitChunksPlugin" class="headerlink" title="SplitChunksPlugin"></a>SplitChunksPlugin</h1><p>官方文档表示，CommonsChunkPlugin 已经从 webpack v4 legato 中移除。而是建议使用 SplitChunksPlugin 来代替 CommonsChunkPlugin。</p>
<p>官方推荐的做法是采用 SplitChunksPlugin 配置，来实现代码的拆分。较新版本的 webpack 中，如果采用之前配置 CommonsChunkPlugin 的方法，会报错，找不到该插件。</p>
<p>通过将公共模块拆出来，最终合成的文件能够在最开始的时候加载一次，便存到缓存中供后续使用。 这个带来速度上的提升，因为浏览器会迅速将公共的代码从缓存中取出来，而不是每次访问一个新页面时，再去加载一个更大的文件。</p>
<p><code>optimization.splitChunks</code>  有默认的配置项，如果在配置文件中开启了该属性，但是没有配置任何参数的话，也是起作用的，因为该属性有默认配置项。例如：</p>
<p><em>webpack.config.js</em></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">'path'</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    entry: <span class="string">'./app.js'</span>,</span><br><span class="line">    output: &#123;</span><br><span class="line">        filename: <span class="string">'bundle.js'</span>,</span><br><span class="line">        path: path.resolve(__dirname, <span class="string">'./dist'</span>)</span><br><span class="line">    &#125;,</span><br><span class="line">    optimization: &#123;</span><br><span class="line">        splitChunks: &#123;&#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>此时也是起作用的，默认配置项目如下：</p>
<p><em>webpack.config.js</em></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">'path'</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    entry: <span class="string">'./app.js'</span>,</span><br><span class="line">    output: &#123;</span><br><span class="line">        filename: <span class="string">'bundle.js'</span>,</span><br><span class="line">        path: path.resolve(__dirname, <span class="string">'./dist'</span>)</span><br><span class="line">    &#125;,</span><br><span class="line">    optimization: &#123;</span><br><span class="line">        splitChunks: &#123;</span><br><span class="line">            chunks: <span class="string">"async"</span>,</span><br><span class="line">            minSize: <span class="number">30000</span>,</span><br><span class="line">            minChunks: <span class="number">1</span>,</span><br><span class="line">            maxAsyncRequests: <span class="number">5</span>,</span><br><span class="line">            maxInitialRequests: <span class="number">3</span>,</span><br><span class="line">            automaticNameDelimiter: <span class="string">'~'</span>,</span><br><span class="line">            name: <span class="literal">true</span>,</span><br><span class="line">            cacheGroups: &#123;</span><br><span class="line">                vendors: &#123;</span><br><span class="line">                    test: <span class="regexp">/[\\/]node_modules[\\/]/</span>,</span><br><span class="line">                    priority: <span class="number">-10</span></span><br><span class="line">                &#125;,</span><br><span class="line">                <span class="keyword">default</span>: &#123;</span><br><span class="line">                    minChunks: <span class="number">2</span>,</span><br><span class="line">                    priority: <span class="number">-20</span>,</span><br><span class="line">                    reuseExistingChunk: <span class="literal">true</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>常见配置项目的说明：</p>
<p><em>webpack.config.js</em></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">'path'</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    entry: <span class="string">'./app.js'</span>,</span><br><span class="line">    output: &#123;</span><br><span class="line">        filename: <span class="string">'bundle.js'</span>,</span><br><span class="line">        path: path.resolve(__dirname, <span class="string">'./dist'</span>)</span><br><span class="line">    &#125;,</span><br><span class="line">    optimization: &#123;</span><br><span class="line">         splitChunks: &#123;</span><br><span class="line">            chunks: <span class="string">"all"</span>, <span class="comment">// 表示有3种可能值"initial", "async"和"all"。表示引入模块的方式是同步、异步、全部，默认异步。</span></span><br><span class="line">            minSize: <span class="number">30000</span>, <span class="comment">// 30kb ,默认大于30kb的包大小的时候才进行代码分割</span></span><br><span class="line">            <span class="comment">// maxSize:50000, // 默认没有此配置，可以不配置，有可能会将一个第三方库再次拆分，不建议配置</span></span><br><span class="line">            minChunks: <span class="number">1</span>, <span class="comment">// 表示当一个模块被用了多少次的时候才进行分割，默认1次，就进行分割</span></span><br><span class="line">            maxAsyncRequests: <span class="number">5</span>, <span class="comment">// 同时加载的模块数量，默认是5个。超过5个后，就不会再进行代码分割了（一般不动该配置）</span></span><br><span class="line">            maxInitialRequests: <span class="number">3</span>, <span class="comment">// 入口文件引入的其他模块，默认3个，超过后不再进行代码分割（一般不动该配置）</span></span><br><span class="line">            automaticNameDelimiter: <span class="string">'~'</span>, <span class="comment">// 组和文件名字之间的连接符</span></span><br><span class="line">            name: <span class="literal">true</span>, <span class="comment">// 表示cache里面的名字有效（一般不动该配置）</span></span><br><span class="line">            cacheGroups: &#123;</span><br><span class="line">                vendors: &#123;</span><br><span class="line">                    test: <span class="regexp">/[\\/]node_modules[\\/]/</span>, <span class="comment">// 检测引入库是否在 node_modules 目录下,是的话打包出来默认名为 vandors~bundule.js。</span></span><br><span class="line">                    priority: <span class="number">-10</span>, <span class="comment">// 优先级（比如 -10 大于 default 中的 -20），同时满足两个配置的话，优先走优先级高的配置</span></span><br><span class="line">                    filename: <span class="string">'vendors.js'</span> <span class="comment">// 修改库打包的文件名为 vendors.js</span></span><br><span class="line">                &#125;,</span><br><span class="line">                <span class="keyword">default</span>: &#123;</span><br><span class="line">                    minChunks: <span class="number">2</span>,</span><br><span class="line">                    priority: <span class="number">-20</span>, <span class="comment">// 优先级（比如 -10 大于 default 中的 -20），同时满足两个配置的话，优先走优先级高的配置</span></span><br><span class="line">                    reuseExistingChunk: <span class="literal">true</span> <span class="comment">// 如果一个模块已经被打包过了，再次遇到相同的模块后，直接复用，而不是再次打包</span></span><br><span class="line">                &#125; <span class="comment">// 如果引入的模块不在node_modules里面，走这个属性的配置</span></span><br><span class="line">            &#125;, <span class="comment">// 缓存组，可以将多个库、模块一起进行分析打包到 vendors 或者 default</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>详见官网：<a href="https://www.webpackjs.com/plugins/split-chunks-plugin/#configuration" target="_blank" rel="noopener">https://www.webpackjs.com/plugins/split-chunks-plugin/#configuration</a></p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/04/15/webpack%E6%87%92%E5%8A%A0%E8%BD%BD%E7%94%A8%E6%B3%95/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://inews.gtimg.com/newsapp_ls/0/12122532695/0">
      <meta itemprop="name" content="Albert Guo">
      <meta itemprop="description" content="郭鹏松的个人博客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Albert Guo">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2020/04/15/webpack%E6%87%92%E5%8A%A0%E8%BD%BD%E7%94%A8%E6%B3%95/" class="post-title-link" itemprop="url">webpack懒加载用法</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-04-15 10:38:22" itemprop="dateCreated datePublished" datetime="2020-04-15T10:38:22+08:00">2020-04-15</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-06-30 16:39:14" itemprop="dateModified" datetime="2020-06-30T16:39:14+08:00">2020-06-30</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/webpack/" itemprop="url" rel="index"><span itemprop="name">webpack</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="懒加载"><a href="#懒加载" class="headerlink" title="懒加载"></a>懒加载</h1><p>懒加载或者按需加载，是一种很好的优化网页或应用的方式。这种方式实际上是先把你的代码在一些逻辑断点处分离开，然后在一些代码块中完成某些操作后，立即引用或即将引用另外一些新的代码块。这样加快了应用的初始加载速度，减轻了它的总体体积，因为某些代码块可能永远不会被加载。</p>
<p>比如一些框架的路由配置，就用到了懒加载技术，点击不同的页面，懒加载不同的打包代码。</p>
<p><em>text.js 数据文件</em></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">return</span> [<span class="string">'白'</span>, <span class="string">'日'</span>, <span class="string">'依'</span>, <span class="string">'山'</span>, <span class="string">'尽'</span>];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><em>a.js 业务代码</em></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> _ <span class="keyword">from</span> <span class="string">'loadsh'</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">component</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> button = <span class="built_in">document</span>.createElement(<span class="string">'button'</span>);</span><br><span class="line">    button.innerText = <span class="string">'生成'</span>;</span><br><span class="line">    <span class="built_in">document</span>.getElementById(<span class="string">'root'</span>).appendChild(button);</span><br><span class="line">    <span class="keyword">let</span> div = <span class="built_in">document</span>.createElement(<span class="string">'div'</span>);</span><br><span class="line"></span><br><span class="line">    button.addEventListener(<span class="string">'click'</span>, () =&gt; &#123;</span><br><span class="line">        <span class="keyword">import</span>(<span class="comment">/* webpackChunkName:"text" */</span> <span class="string">'./text'</span>).then(<span class="function"><span class="params">module</span> =&gt;</span> &#123;</span><br><span class="line">            div.innerText = _.join(<span class="built_in">module</span>.default(), <span class="string">'~'</span>);</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">return</span> div;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">document</span>.getElementById(<span class="string">'root'</span>).appendChild(component());</span><br></pre></td></tr></table></figure>

<p><em>app.js 入口文件</em></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="string">'./a'</span>;</span><br></pre></td></tr></table></figure>

<p>页面初始化，并不会加载 text 部分的打包代码，而是在点击按钮后，才去加载这个打包的代码。</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/12/15/postcss-loader-%E8%87%AA%E5%8A%A8%E6%B7%BB%E5%8A%A0%E6%A0%B7%E5%BC%8F%E5%89%8D%E7%BC%80/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://inews.gtimg.com/newsapp_ls/0/12122532695/0">
      <meta itemprop="name" content="Albert Guo">
      <meta itemprop="description" content="郭鹏松的个人博客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Albert Guo">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2019/12/15/postcss-loader-%E8%87%AA%E5%8A%A8%E6%B7%BB%E5%8A%A0%E6%A0%B7%E5%BC%8F%E5%89%8D%E7%BC%80/" class="post-title-link" itemprop="url">postcss-loader 自动添加样式前缀</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-12-15 20:38:22" itemprop="dateCreated datePublished" datetime="2019-12-15T20:38:22+08:00">2019-12-15</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-08 20:48:14" itemprop="dateModified" datetime="2020-07-08T20:48:14+08:00">2020-07-08</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/webpack/" itemprop="url" rel="index"><span itemprop="name">webpack</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h2 id="处理-css3-兼容前缀"><a href="#处理-css3-兼容前缀" class="headerlink" title="处理 css3 兼容前缀"></a>处理 css3 兼容前缀</h2><p><code>postcss-loader</code> 可以将打包编译过的 <code>css</code> 样式文件，自动添加一些兼容前缀，例如 <code>-webkit-</code> 等。</p>
<h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">npm install --save-dev postcss-loader   &#x2F;&#x2F; 安装 postcss-loader</span><br><span class="line">npm install --save-dev autoprefixer   &#x2F;&#x2F; 安装 autoprefixer 自动加前缀插件</span><br></pre></td></tr></table></figure>

<h3 id="配置"><a href="#配置" class="headerlink" title="配置"></a>配置</h3><p>需要在 <em>webpack.config.js</em> 同级目录下创建 <em>postcss.config.js</em>，添加相关插件配置。</p>
<p><em>postcss.config.js</em></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    plugins: [</span><br><span class="line">        <span class="built_in">require</span>(<span class="string">'autoprefixer'</span>)</span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在 webpack 配置文件中添加样式相关等 <code>postcss-loader</code>。</p>
<p><em>webpack.config.js</em></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">const path &#x3D; require(&#39;path&#39;);</span><br><span class="line"></span><br><span class="line">module.exports &#x3D; &#123;</span><br><span class="line">    entry: &#39;.&#x2F;app.js&#39;,</span><br><span class="line">    output: &#123;</span><br><span class="line">        filename: &#39;bundle.js&#39;,</span><br><span class="line">        path: path.resolve(__dirname, &#39;dist&#39;)</span><br><span class="line">    &#125;,</span><br><span class="line">    module: &#123;</span><br><span class="line">        rules: [</span><br><span class="line">            &#123;</span><br><span class="line">                test: &#x2F;\.css$&#x2F;,</span><br><span class="line">                use: [</span><br><span class="line">                    &#39;style-loader&#39;,</span><br><span class="line">                    &#39;css-loader&#39;,</span><br><span class="line">                    &#39;postcss-loader&#39;</span><br><span class="line">                ]</span><br><span class="line">            &#125;,</span><br><span class="line">            &#123;</span><br><span class="line">                test: &#x2F;\.(jpg|png|jpeg|gif)$&#x2F;,</span><br><span class="line">                use: [&quot;file-loader&quot;]</span><br><span class="line">            &#125;,</span><br><span class="line">            &#123;</span><br><span class="line">                test: &#x2F;\.(scss|sass)$&#x2F;,</span><br><span class="line">                use: [&quot;style-loader&quot;, &quot;css-loader&quot;, &quot;postcss-loader&quot;, &quot;sass-loader&quot;]</span><br><span class="line">            &#125;</span><br><span class="line">        ]</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>webpack 4.X 以上，需要在 <code>package.json</code> 文件中配置浏览器支持参数 <code>browserslist</code>。</p>
<p><em>package.json</em></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  &quot;name&quot;: &quot;webpack-demo&quot;,</span><br><span class="line">  &quot;version&quot;: &quot;1.0.0&quot;,</span><br><span class="line">  &quot;description&quot;: &quot;&quot;,</span><br><span class="line">  &quot;main&quot;: &quot;app.js&quot;,</span><br><span class="line">  &quot;dependencies&quot;: &#123;</span><br><span class="line">    &quot;webpack&quot;: &quot;^4.42.1&quot;,</span><br><span class="line">    &quot;webpack-cli&quot;: &quot;^3.3.11&quot;</span><br><span class="line">  &#125;,</span><br><span class="line">  &quot;devDependencies&quot;: &#123;</span><br><span class="line">    &quot;autoprefixer&quot;: &quot;^9.7.6&quot;,</span><br><span class="line">    &quot;css-loader&quot;: &quot;^3.5.2&quot;,</span><br><span class="line">    &quot;file-loader&quot;: &quot;^6.0.0&quot;,</span><br><span class="line">    &quot;node-sass&quot;: &quot;^4.13.1&quot;,</span><br><span class="line">    &quot;postcss-loader&quot;: &quot;^3.0.0&quot;,</span><br><span class="line">    &quot;sass-loader&quot;: &quot;^8.0.2&quot;,</span><br><span class="line">    &quot;style-loader&quot;: &quot;^1.1.4&quot;,</span><br><span class="line">    &quot;url-loader&quot;: &quot;^4.1.0&quot;</span><br><span class="line">  &#125;,</span><br><span class="line">  &quot;scripts&quot;: &#123;</span><br><span class="line">    &quot;build&quot;: &quot;webpack&quot;</span><br><span class="line">  &#125;,</span><br><span class="line">  &quot;author&quot;: &quot;&quot;,</span><br><span class="line">  &quot;license&quot;: &quot;ISC&quot;,</span><br><span class="line">  &quot;browserslist&quot;: [</span><br><span class="line">    &quot;defaults&quot;,</span><br><span class="line">    &quot;not ie &lt; 11&quot;,</span><br><span class="line">    &quot;last 2 versions&quot;,</span><br><span class="line">    &quot;&gt; 1%&quot;,</span><br><span class="line">    &quot;iOS 7&quot;,</span><br><span class="line">    &quot;last 3 iOS versions&quot;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后在打包完成的项目样式就，就可以以看到添加了前缀的样式效果了。</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-class">.pic-container</span> &#123;</span><br><span class="line">    <span class="attribute">width</span>: <span class="number">80px</span>;</span><br><span class="line">    <span class="attribute">height</span>: <span class="number">80px</span>;</span><br><span class="line">    <span class="attribute">border-radius</span>: <span class="number">100px</span>;</span><br><span class="line">    <span class="attribute">overflow</span>: hidden;</span><br><span class="line">    <span class="attribute">margin</span>: <span class="number">10px</span>;</span><br><span class="line">    <span class="attribute">-webkit-transform</span>: <span class="built_in">translate</span>(<span class="number">40px</span>, <span class="number">40px</span>);</span><br><span class="line">    <span class="attribute">transform</span>: <span class="built_in">translate</span>(<span class="number">40px</span>, <span class="number">40px</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/04/29/npm-%E4%BD%BF%E7%94%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://inews.gtimg.com/newsapp_ls/0/12122532695/0">
      <meta itemprop="name" content="Albert Guo">
      <meta itemprop="description" content="郭鹏松的个人博客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Albert Guo">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2019/04/29/npm-%E4%BD%BF%E7%94%A8/" class="post-title-link" itemprop="url">npm 使用教程</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-04-29 19:28:56" itemprop="dateCreated datePublished" datetime="2019-04-29T19:28:56+08:00">2019-04-29</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-06-29 20:03:35" itemprop="dateModified" datetime="2020-06-29T20:03:35+08:00">2020-06-29</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/nodejs/" itemprop="url" rel="index"><span itemprop="name">nodejs</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <blockquote>
<p>声明，本教程摘录于菜鸟官网，非本人原创。文中部分内容来自于个人工作积累编写，仅供学习参考。</p>
</blockquote>
<p>原创网址： <a href="https://www.runoob.com/nodejs/nodejs-npm.html" target="_blank" rel="noopener">菜鸟教程</a></p>
<h1 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h1><p>NPM 是随同 NodeJS 一起安装的包管理工具，能解决 NodeJS 代码部署上的很多问题，常见的使用场景有以下几种：</p>
<ul>
<li>允许用户从 NPM 服务器下载别人编写的第三方包到本地使用。</li>
<li>允许用户从 NPM 服务器下载并安装别人编写的命令行程序到本地使用。</li>
<li>允许用户将自己编写的包或命令行程序上传到 NPM 服务器供别人使用。</li>
</ul>
<p>由于新版的 nodejs 已经集成了 npm ，所以之前 npm 也一并安装好了。同样可以通过输入 <code>&quot;npm -v&quot;</code> 来测试是否成功安装。命令如下，出现版本提示表示安装成功:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ npm -v</span><br><span class="line">2.3.0</span><br></pre></td></tr></table></figure>

<p>如果你安装的是旧版本的 npm，可以很容易得通过 npm 命令来升级，命令如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$ sudo npm install npm -g</span><br><span class="line">&#x2F;usr&#x2F;local&#x2F;bin&#x2F;npm -&gt; &#x2F;usr&#x2F;local&#x2F;lib&#x2F;node_modules&#x2F;npm&#x2F;bin&#x2F;npm-cli.js</span><br><span class="line">npm@2.14.2 &#x2F;usr&#x2F;local&#x2F;lib&#x2F;node_modules&#x2F;npm</span><br></pre></td></tr></table></figure>

<p>如果是 Window 系统使用以下命令即可：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install npm -g</span><br></pre></td></tr></table></figure>

<p>使用淘宝镜像的命令：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install -g cnpm --registry&#x3D;https:&#x2F;&#x2F;registry.npm.taobao.org</span><br></pre></td></tr></table></figure>

<h1 id="使用-npm-命令安装模块"><a href="#使用-npm-命令安装模块" class="headerlink" title="使用 npm 命令安装模块"></a>使用 npm 命令安装模块</h1><p><code>npm</code> 安装 Node.js 模块语法格式如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm install &lt;Module Name&gt;</span><br></pre></td></tr></table></figure>

<p>以下实例，我们使用 npm 命令安装常用的 Node.js web 框架模块 express :</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm install express</span><br></pre></td></tr></table></figure>

<p>安装好之后，<code>express</code> 包就放在了工程目录下的 <code>node_modules</code> 目录中，因此在代码中只需要通过 <code>require(&#39;express&#39;)</code> 的方式就好，无需指定第三方包路径。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>);</span><br></pre></td></tr></table></figure>

<h1 id="全局安装与本地安装"><a href="#全局安装与本地安装" class="headerlink" title="全局安装与本地安装"></a>全局安装与本地安装</h1><p>==npm 的包安装分为本地安装（local）、全局安装（global）两种。== 至于选择哪种方式来安装，取决于我们如何使用这个包。</p>
<ul>
<li>如果你自己的模块依赖于某个包，并通过 Node.js 的 require 加载，那么你应该选择本地安装，这种方式也是 npm install 命令的默认行为。</li>
<li>如果你想将包作为一个命令行工具，（比如 grunt CLI），那么你应该选择全局安装。</li>
</ul>
<p>从敲的命令行来看，差别只是有没有 <code>-g</code> 而已，比如</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">npm install express      # 本地安装</span><br><span class="line">npm install express -g   # 全局安装</span><br></pre></td></tr></table></figure>

<p>如果出现以下错误：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm err! Error: connect ECONNREFUSED 127.0.0.1:8087</span><br></pre></td></tr></table></figure>

<p>解决办法为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm config set proxy null</span><br></pre></td></tr></table></figure>

<h2 id="本地安装"><a href="#本地安装" class="headerlink" title="本地安装"></a>本地安装</h2><ol>
<li>将安装包放在 <code>./node_modules</code> 下（==运行 npm 命令时所在的目录==），如果没有 <code>node_modules</code> 目录，会在当前执行 <code>npm</code> 命令的目录下生成 <code>node_modules</code> 目录。</li>
<li>可以通过 <code>require()</code> 来引入本地安装的包。</li>
</ol>
<h2 id="全局安装"><a href="#全局安装" class="headerlink" title="全局安装"></a>全局安装</h2><ol>
<li>将安装包放在 <code>/usr/local</code> 下或者你 <code>node</code> 的安装目录。</li>
<li>可以直接在命令行里使用。<br>如果你希望具备两者功能，则需要在两个地方安装它或使用 <code>npm link</code>。</li>
</ol>
<p>接下来我们使用全局方式安装 express 。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm install express -g</span><br></pre></td></tr></table></figure>

<p>安装过程输出如下内容，第一行输出了模块的版本号及安装位置。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">express@4.13.3 node_modules&#x2F;express</span><br><span class="line">├── escape-html@1.0.2</span><br><span class="line">├── range-parser@1.0.2</span><br><span class="line">├── merge-descriptors@1.0.0</span><br><span class="line">├── array-flatten@1.1.1</span><br><span class="line">├── cookie@0.1.3</span><br><span class="line">├── utils-merge@1.0.0</span><br><span class="line">├── parseurl@1.3.0</span><br><span class="line">├── cookie-signature@1.0.6</span><br><span class="line">├── methods@1.1.1</span><br><span class="line">├── fresh@0.3.0</span><br><span class="line">├── vary@1.0.1</span><br><span class="line">├── path-to-regexp@0.1.7</span><br><span class="line">├── content-type@1.0.1</span><br><span class="line">├── etag@1.7.0</span><br><span class="line">├── serve-static@1.10.0</span><br><span class="line">├── content-disposition@0.5.0</span><br><span class="line">├── depd@1.0.1</span><br><span class="line">├── qs@4.0.0</span><br><span class="line">├── finalhandler@0.4.0 (unpipe@1.0.0)</span><br><span class="line">├── on-finished@2.3.0 (ee-first@1.1.1)</span><br><span class="line">├── proxy-addr@1.0.8 (forwarded@0.1.0, ipaddr.js@1.0.1)</span><br><span class="line">├── debug@2.2.0 (ms@0.7.1)</span><br><span class="line">├── type-is@1.6.8 (media-typer@0.3.0, mime-types@2.1.6)</span><br><span class="line">├── accepts@1.2.12 (negotiator@0.5.3, mime-types@2.1.6)</span><br><span class="line">└── send@0.13.0 (destroy@1.0.3, statuses@1.2.1, ms@0.7.1, mime@1.3.4, http-errors@1.3.1)</span><br></pre></td></tr></table></figure>

<h2 id="查看安装信息"><a href="#查看安装信息" class="headerlink" title="查看安装信息"></a>查看安装信息</h2><p>你可以使用以下命令来查看所有全局安装的模块：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">$ npm list -g</span><br><span class="line"></span><br><span class="line">├─┬ cnpm@4.3.2</span><br><span class="line">│ ├── auto-correct@1.0.0</span><br><span class="line">│ ├── bagpipe@0.3.5</span><br><span class="line">│ ├── colors@1.1.2</span><br><span class="line">│ ├─┬ commander@2.9.0</span><br><span class="line">│ │ └── graceful-readlink@1.0.1</span><br><span class="line">│ ├─┬ cross-spawn@0.2.9</span><br><span class="line">│ │ └── lru-cache@2.7.3</span><br><span class="line">……</span><br></pre></td></tr></table></figure>

<p>如果要查看某个模块的版本号，可以使用命令如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$ npm list grunt</span><br><span class="line"></span><br><span class="line">projectName@projectVersion &#x2F;path&#x2F;to&#x2F;project&#x2F;folder</span><br><span class="line">└── grunt@0.4.1</span><br></pre></td></tr></table></figure>

<h1 id="几种安装方式的区别-g、–save、–save-dev"><a href="#几种安装方式的区别-g、–save、–save-dev" class="headerlink" title="几种安装方式的区别(-g、–save、–save-dev)"></a>几种安装方式的区别(-g、–save、–save-dev)</h1><p>使用 <code>npm install</code> 安装模块的模块的时候 ，一般会使用下面这几种命令形式:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">npm install moduleName # 安装模块到项目目录下</span><br><span class="line"> </span><br><span class="line">npm install -g moduleName # -g 的意思是将模块安装到全局，具体安装到磁盘哪个位置，要看 npm config prefix 的位置。</span><br><span class="line"> </span><br><span class="line">npm install -save moduleName # -save 的意思是将模块安装到项目目录下，并在 package 文件的 dependencies 节点写入依赖。</span><br><span class="line"> </span><br><span class="line">npm install -save-dev moduleName # -save-dev 的意思是将模块安装到项目目录下，并在 package 文件的 devDependencies 节点写入依赖。</span><br></pre></td></tr></table></figure>

<h2 id="npm-install-moduleName-命令"><a href="#npm-install-moduleName-命令" class="headerlink" title="npm install moduleName 命令"></a>npm install moduleName 命令</h2><ol>
<li>安装模块到项目 <code>node_modules</code> 目录下。</li>
<li>不会将模块依赖写入 <code>devDependencies</code> 或 <code>dependencies</code> 节点。</li>
<li>运行 <code>npm install</code> 初始化项目时==不会下载模块。==</li>
</ol>
<h2 id="npm-install-g-moduleName-命令"><a href="#npm-install-g-moduleName-命令" class="headerlink" title="npm install -g moduleName 命令"></a>npm install -g moduleName 命令</h2><ol>
<li>安装模块到全局，不会在项目 <code>node_modules</code> 目录中保存模块包。</li>
<li>不会将模块依赖写入 <code>devDependencies</code> 或 <code>dependencies</code> 节点。</li>
<li>运行 npm install 初始化项目时==不会下载模块。==</li>
</ol>
<h2 id="npm-install-save-moduleName-命令"><a href="#npm-install-save-moduleName-命令" class="headerlink" title="npm install -save moduleName 命令"></a>npm install -save moduleName 命令</h2><ol>
<li>安装模块到项目 <code>node_modules</code> 目录下。</li>
<li>会将模块依赖写入 <code>dependencies</code> 节点。</li>
<li>运行 <code>npm install</code> 初始化项目时，会将模块下载到项目目录下。</li>
<li>运行 <code>npm install --production</code>  或者注明 <code>NODE_ENV</code> 变量值为 <code>production</code> 时，会自动下载模块到 <code>node_modules</code> 目录中。</li>
</ol>
<h2 id="npm-install-save-dev-moduleName-命令"><a href="#npm-install-save-dev-moduleName-命令" class="headerlink" title="npm install -save-dev moduleName 命令"></a>npm install -save-dev moduleName 命令</h2><ol>
<li>安装模块到项目 <code>node_modules</code> 目录下。</li>
<li>会将模块依赖写入 <code>devDependencies</code> 节点。</li>
<li>运行 <code>npm install</code> 初始化项目时，会将模块下载到项目目录下。</li>
<li>运行 <code>npm install --production</code>  或者注明 <code>NODE_ENV</code> 变量值为 <code>production</code> 时，不会自动下载模块到 <code>node_modules</code> 目录中。</li>
</ol>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p><code>devDependencies</code> 节点下的模块是我们在开发时需要用的，比如项目中使用的 <code>gulp</code> ，压缩 <code>css、js</code> 的模块。这些模块在我们的项目部署后是不需要的，所以我们可以使用 <code>-save-dev</code> 的形式安装。像 <code>express</code> 这些模块是项目运行必备的，应该安装在 <code>dependencies</code> 节点下，所以我们应该使用 <code>-save</code> 的形式安装。</p>
<p>在安装一个要打包到生产环境的安装包时，你应该使用 <code>npm install --save</code>，如果你在安装一个用于开发环境的安装包（例如，linter, 测试库等），你应该使用 <code>npm install --save-dev</code>。</p>
<h1 id="使用-package-json"><a href="#使用-package-json" class="headerlink" title="使用 package.json"></a>使用 package.json</h1><p><code>package.json</code> 位于模块的目录下，用于定义包的属性。接下来让我们来看下 <code>express</code> 包的 <code>package.json</code> 文件，位于 <code>node_modules/express/package.json</code> 内容：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">"name"</span>: <span class="string">"express"</span>, <span class="comment">// 项目名称</span></span><br><span class="line">  <span class="string">"description"</span>: <span class="string">"Fast, unopinionated, minimalist web framework"</span>, <span class="comment">// 项目描述</span></span><br><span class="line">  <span class="string">"version"</span>: <span class="string">"4.13.3"</span>, <span class="comment">// 版本</span></span><br><span class="line">  <span class="string">"private"</span>: <span class="literal">true</span>, <span class="comment">// 是否是私有项目（true 是）</span></span><br><span class="line">  <span class="string">"author"</span>: &#123;</span><br><span class="line">    <span class="string">"name"</span>: <span class="string">"TJ Holowaychuk"</span>, <span class="comment">// 作者姓名</span></span><br><span class="line">    <span class="string">"email"</span>: <span class="string">"tj@vision-media.ca"</span> <span class="comment">// 作者邮箱</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">"contributors"</span>: [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="string">"name"</span>: <span class="string">"Aaron Heckmann"</span>,</span><br><span class="line">      <span class="string">"email"</span>: <span class="string">"aaron.heckmann+github@gmail.com"</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="string">"name"</span>: <span class="string">"Ciaran Jessup"</span>,</span><br><span class="line">      <span class="string">"email"</span>: <span class="string">"ciaranj@gmail.com"</span></span><br><span class="line">    &#125;</span><br><span class="line">  ], <span class="comment">// 其他贡献者</span></span><br><span class="line">  <span class="string">"license"</span>: <span class="string">"MIT"</span>, <span class="comment">// 开源协议</span></span><br><span class="line">  <span class="string">"repository"</span>: &#123;</span><br><span class="line">    <span class="string">"type"</span>: <span class="string">"git"</span>,</span><br><span class="line">    <span class="string">"url"</span>: <span class="string">"git+https://github.com/strongloop/express.git"</span></span><br><span class="line">  &#125;, <span class="comment">// 仓库地址</span></span><br><span class="line">  <span class="string">"homepage"</span>: <span class="string">"http://expressjs.com/"</span>, <span class="comment">// 主页网址</span></span><br><span class="line">  <span class="string">"keywords"</span>: [</span><br><span class="line">    <span class="string">"express"</span>,</span><br><span class="line">    <span class="string">"framework"</span>,</span><br><span class="line">    <span class="string">"sinatra"</span></span><br><span class="line">  ], <span class="comment">// 关键字</span></span><br><span class="line">  <span class="string">"dependencies"</span>: &#123;</span><br><span class="line">    <span class="string">"accepts"</span>: <span class="string">"~1.2.12"</span>,</span><br><span class="line">    <span class="string">"array-flatten"</span>: <span class="string">"1.1.1"</span>,</span><br><span class="line">    <span class="string">"content-disposition"</span>: <span class="string">"0.5.0"</span>,</span><br><span class="line">    <span class="string">"content-type"</span>: <span class="string">"~1.0.1"</span>,</span><br><span class="line">    <span class="string">"cookie"</span>: <span class="string">"0.1.3"</span>,</span><br><span class="line">    <span class="string">"cookie-signature"</span>: <span class="string">"1.0.6"</span>,</span><br><span class="line">    <span class="string">"debug"</span>: <span class="string">"~2.2.0"</span>,</span><br><span class="line">    <span class="string">"depd"</span>: <span class="string">"~1.0.1"</span>,</span><br><span class="line">    <span class="string">"escape-html"</span>: <span class="string">"1.0.2"</span>,</span><br><span class="line">    <span class="string">"etag"</span>: <span class="string">"~1.7.0"</span>,</span><br><span class="line">    <span class="string">"finalhandler"</span>: <span class="string">"0.4.0"</span>,</span><br><span class="line">    <span class="string">"fresh"</span>: <span class="string">"0.3.0"</span>,</span><br><span class="line">    <span class="string">"merge-descriptors"</span>: <span class="string">"1.0.0"</span>,</span><br><span class="line">    <span class="string">"methods"</span>: <span class="string">"~1.1.1"</span>,</span><br><span class="line">    <span class="string">"on-finished"</span>: <span class="string">"~2.3.0"</span>,</span><br><span class="line">    <span class="string">"parseurl"</span>: <span class="string">"~1.3.0"</span>,</span><br><span class="line">    <span class="string">"path-to-regexp"</span>: <span class="string">"0.1.7"</span>,</span><br><span class="line">    <span class="string">"proxy-addr"</span>: <span class="string">"~1.0.8"</span>,</span><br><span class="line">    <span class="string">"qs"</span>: <span class="string">"4.0.0"</span>,</span><br><span class="line">    <span class="string">"range-parser"</span>: <span class="string">"~1.0.2"</span>,</span><br><span class="line">    <span class="string">"send"</span>: <span class="string">"0.13.0"</span>,</span><br><span class="line">    <span class="string">"serve-static"</span>: <span class="string">"~1.10.0"</span>,</span><br><span class="line">    <span class="string">"type-is"</span>: <span class="string">"~1.6.6"</span>,</span><br><span class="line">    <span class="string">"utils-merge"</span>: <span class="string">"1.0.0"</span>,</span><br><span class="line">    <span class="string">"vary"</span>: <span class="string">"~1.0.1"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">"devDependencies"</span>: &#123;</span><br><span class="line">    <span class="string">"after"</span>: <span class="string">"0.8.1"</span>,</span><br><span class="line">    <span class="string">"ejs"</span>: <span class="string">"2.3.3"</span>,</span><br><span class="line">    <span class="string">"istanbul"</span>: <span class="string">"0.3.17"</span>,</span><br><span class="line">    <span class="string">"marked"</span>: <span class="string">"0.3.5"</span>,</span><br><span class="line">    <span class="string">"mocha"</span>: <span class="string">"2.2.5"</span>,</span><br><span class="line">    <span class="string">"should"</span>: <span class="string">"7.0.2"</span>,</span><br><span class="line">    <span class="string">"supertest"</span>: <span class="string">"1.0.1"</span>,</span><br><span class="line">    <span class="string">"body-parser"</span>: <span class="string">"~1.13.3"</span>,</span><br><span class="line">    <span class="string">"connect-redis"</span>: <span class="string">"~2.4.1"</span>,</span><br><span class="line">    <span class="string">"cookie-parser"</span>: <span class="string">"~1.3.5"</span>,</span><br><span class="line">    <span class="string">"cookie-session"</span>: <span class="string">"~1.2.0"</span>,</span><br><span class="line">    <span class="string">"express-session"</span>: <span class="string">"~1.11.3"</span>,</span><br><span class="line">    <span class="string">"jade"</span>: <span class="string">"~1.11.0"</span>,</span><br><span class="line">    <span class="string">"method-override"</span>: <span class="string">"~2.3.5"</span>,</span><br><span class="line">    <span class="string">"morgan"</span>: <span class="string">"~1.6.1"</span>,</span><br><span class="line">    <span class="string">"multiparty"</span>: <span class="string">"~4.1.2"</span>,</span><br><span class="line">    <span class="string">"vhost"</span>: <span class="string">"~3.0.1"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">"engines"</span>: &#123;</span><br><span class="line">    <span class="string">"node"</span>: <span class="string">"&gt;= 0.10.0"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">"files"</span>: [</span><br><span class="line">    <span class="string">"LICENSE"</span>,</span><br><span class="line">    <span class="string">"History.md"</span>,</span><br><span class="line">    <span class="string">"Readme.md"</span>,</span><br><span class="line">    <span class="string">"index.js"</span>,</span><br><span class="line">    <span class="string">"lib/"</span></span><br><span class="line">  ],</span><br><span class="line">  <span class="string">"scripts"</span>: &#123;</span><br><span class="line">    <span class="string">"test"</span>: <span class="string">"mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/"</span>,</span><br><span class="line">    <span class="string">"test-ci"</span>: <span class="string">"istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/ test/acceptance/"</span>,</span><br><span class="line">    <span class="string">"test-cov"</span>: <span class="string">"istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/"</span>,</span><br><span class="line">    <span class="string">"test-tap"</span>: <span class="string">"mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">"gitHead"</span>: <span class="string">"ef7ad681b245fba023843ce94f6bcb8e275bbb8e"</span>,</span><br><span class="line">  <span class="string">"bugs"</span>: &#123;</span><br><span class="line">    <span class="string">"url"</span>: <span class="string">"https://github.com/strongloop/express/issues"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">"_id"</span>: <span class="string">"express@4.13.3"</span>,</span><br><span class="line">  <span class="string">"_shasum"</span>: <span class="string">"ddb2f1fb4502bf33598d2b032b037960ca6c80a3"</span>,</span><br><span class="line">  <span class="string">"_from"</span>: <span class="string">"express@*"</span>,</span><br><span class="line">  <span class="string">"_npmVersion"</span>: <span class="string">"1.4.28"</span>,</span><br><span class="line">  <span class="string">"_npmUser"</span>: &#123;</span><br><span class="line">    <span class="string">"name"</span>: <span class="string">"dougwilson"</span>,</span><br><span class="line">    <span class="string">"email"</span>: <span class="string">"doug@somethingdoug.com"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">"maintainers"</span>: [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="string">"name"</span>: <span class="string">"tjholowaychuk"</span>,</span><br><span class="line">      <span class="string">"email"</span>: <span class="string">"tj@vision-media.ca"</span></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="string">"name"</span>: <span class="string">"jongleberry"</span>,</span><br><span class="line">      <span class="string">"email"</span>: <span class="string">"jonathanrichardong@gmail.com"</span></span><br><span class="line">    &#125;</span><br><span class="line">  ],</span><br><span class="line">  <span class="string">"dist"</span>: &#123;</span><br><span class="line">    <span class="string">"shasum"</span>: <span class="string">"ddb2f1fb4502bf33598d2b032b037960ca6c80a3"</span>,</span><br><span class="line">    <span class="string">"tarball"</span>: <span class="string">"http://registry.npmjs.org/express/-/express-4.13.3.tgz"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">"directories"</span>: &#123;&#125;,</span><br><span class="line">  <span class="string">"_resolved"</span>: <span class="string">"https://registry.npmjs.org/express/-/express-4.13.3.tgz"</span>,</span><br><span class="line">  <span class="string">"readme"</span>: <span class="string">"ERROR: No README data found!"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="Package-json-属性说明"><a href="#Package-json-属性说明" class="headerlink" title="Package.json 属性说明"></a>Package.json 属性说明</h1><ul>
<li>name - 包名。</li>
<li>version - 包的版本号。</li>
<li>description - 包的描述。</li>
<li>homepage - 包的官网 url 。</li>
<li>author - 包的作者姓名。</li>
<li>contributors - 包的其他贡献者姓名。</li>
<li>dependencies - 依赖包列表。如果依赖包没有安装，npm 会自动将依赖包安装在 node_module 目录下。</li>
<li>repository - 包代码存放的地方的类型，可以是 git 或 svn，git 可在 Github 上。</li>
<li>main - main 字段指定了程序的主入口文件，require(‘moduleName’) 就会加载这个文件。这个字段的默认值是模块根目录下面的 index.js。</li>
<li>keywords - 关键字</li>
</ul>
<h1 id="卸载模块"><a href="#卸载模块" class="headerlink" title="卸载模块"></a>卸载模块</h1><p>我们可以使用以下命令来卸载 Node.js 模块。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm uninstall express</span><br></pre></td></tr></table></figure>

<p>卸载后，你可以到 /node_modules/ 目录下查看包是否还存在，或者使用以下命令查看：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm ls</span><br></pre></td></tr></table></figure>

<h1 id="更新模块"><a href="#更新模块" class="headerlink" title="更新模块"></a>更新模块</h1><p>我们可以使用以下命令更新指定模块，例如更新 <code>express</code> 模块：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm update express</span><br></pre></td></tr></table></figure>

<h1 id="搜索模块"><a href="#搜索模块" class="headerlink" title="搜索模块"></a>搜索模块</h1><p>使用以下来搜索模块，例如搜索 <code>express</code> 模块：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm search express</span><br></pre></td></tr></table></figure>

<h1 id="创建模块"><a href="#创建模块" class="headerlink" title="创建模块"></a>创建模块</h1><p>创建模块，package.json 文件是必不可少的。我们可以使用 NPM 生成 package.json 文件，生成的文件包含了基本的结果。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">$ npm init</span><br><span class="line"></span><br><span class="line">This utility will walk you through creating a package.json file.</span><br><span class="line">It only covers the most common items, and tries to guess sensible defaults.</span><br><span class="line"></span><br><span class="line">See &#96;npm help json&#96; for definitive documentation on these fields</span><br><span class="line">and exactly what they do.</span><br><span class="line"></span><br><span class="line">Use &#96;npm install &lt;pkg&gt; --save&#96; afterwards to install a package and</span><br><span class="line">save it as a dependency in the package.json file.</span><br><span class="line"></span><br><span class="line">Press ^C at any time to quit.</span><br><span class="line"></span><br><span class="line">name: (node_modules) runoob                   # 模块名</span><br><span class="line">version: (1.0.0) </span><br><span class="line">description: Node.js 测试模块(www.runoob.com)  # 描述</span><br><span class="line">entry point: (index.js) </span><br><span class="line">test command: make test</span><br><span class="line">git repository: https:&#x2F;&#x2F;github.com&#x2F;runoob&#x2F;runoob.git  # Github 地址</span><br><span class="line">keywords: </span><br><span class="line">author: </span><br><span class="line">license: (ISC) </span><br><span class="line">About to write to ……&#x2F;node_modules&#x2F;package.json:      # 生成地址</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">  &quot;name&quot;: &quot;runoob&quot;,</span><br><span class="line">  &quot;version&quot;: &quot;1.0.0&quot;,</span><br><span class="line">  &quot;description&quot;: &quot;Node.js 测试模块(www.runoob.com)&quot;,</span><br><span class="line">  ……</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Is this ok? (yes) yes</span><br></pre></td></tr></table></figure>

<p>以上的信息，你需要根据你自己的情况输入。在最后输入 <code>&quot;yes&quot;</code> 后会生成 <code>package.json</code> 文件。</p>
<p>接下来我们可以使用以下命令在 npm 资源库中注册用户（使用邮箱注册）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">$ npm adduser</span><br><span class="line"></span><br><span class="line">Username: mcmohd</span><br><span class="line">Password:</span><br><span class="line">Email: (this IS public) mcmohd@gmail.com</span><br></pre></td></tr></table></figure>

<p>接下来我们就用以下命令来发布模块：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm publish</span><br></pre></td></tr></table></figure>

<p>如果你以上的步骤都操作正确，你就可以跟其他模块一样使用 npm 来安装。</p>
<h1 id="版本号"><a href="#版本号" class="headerlink" title="版本号"></a>版本号</h1><p>使用 NPM 下载和发布代码时都会接触到版本号。NPM 使用语义版本号来管理代码，这里简单介绍一下。</p>
<p>==语义版本号分为 X.Y.Z 三位，分别代表主版本号、次版本号和补丁版本号。== 当代码变更时，版本号按以下原则更新。</p>
<ul>
<li>如果只是修复bug，需要更新Z位。</li>
<li>如果是新增了功能，但是向下兼容，需要更新Y位。</li>
<li>如果有大变动，向下不兼容，需要更新X位。</li>
</ul>
<p>版本号有了这个保证后，在申明第三方包依赖时，除了可依赖于一个固定版本号外，还可依赖于某个范围的版本号。例如 <code>&quot;argv&quot;: &quot;0.0.x&quot;</code> 表示依赖于 <code>0.0.x</code> 系列的最新版 <code>argv</code>。</p>
<h1 id="NPM-常用命令"><a href="#NPM-常用命令" class="headerlink" title="NPM 常用命令"></a>NPM 常用命令</h1><p>除了本章介绍的部分外，NPM还提供了很多功能，<code>package.json</code> 里也有很多其它有用的字段。</p>
<p>除了可以在 <code>npmjs.org/doc/</code>  查看官方文档外，这里再介绍一些NPM常用命令。</p>
<ul>
<li>NPM 提供了很多命令，例如 <code>install</code> 和 <code>publish</code> ，使用 <code>npm help</code> 可查看所有命令。</li>
<li>使用 <code>npm help &lt;command&gt;</code> 可查看某条命令的详细帮助，例如 <code>npm help install</code>。</li>
<li>在 <code>package.json</code> 所在目录下使用 <code>npm install . -g</code>  可先在本地安装当前命令行程序，可用于发布前的本地测试。</li>
<li>使用 <code>npm update &lt;package&gt;</code> 可以把当前目录下 <code>node_modules</code> 子目录里边的对应模块更新至最新版本。</li>
<li>使用 <code>npm update &lt;package&gt; -g</code> 可以把全局安装的对应命令行程序更新至最新版。</li>
<li>使用 <code>npm cache clear</code> 可以清空 NPM 本地缓存，用于对付使用相同版本号发布新版本代码的人。</li>
<li>使用 <code>npm unpublish &lt;package&gt;@&lt;version&gt;</code> 可以撤销发布自己发布过的某个版本代码。</li>
</ul>
<h1 id="使用淘宝-NPM-镜像"><a href="#使用淘宝-NPM-镜像" class="headerlink" title="使用淘宝 NPM 镜像"></a>使用淘宝 NPM 镜像</h1><p>淘宝 NPM 镜像是一个完整 npmjs.org 镜像，你可以用此代替官方版本(只读)，同步频率目前为 10分钟 一次以保证尽量与官方服务同步。</p>
<p>你可以使用淘宝定制的 <code>cnpm</code> (gzip 压缩支持) 命令行工具代替默认的 <code>npm</code> :</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm install -g cnpm --registry&#x3D;https:&#x2F;&#x2F;registry.npm.taobao.org</span><br></pre></td></tr></table></figure>

<p>这样就可以使用 cnpm 命令来安装模块了：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ cnpm install [name]</span><br></pre></td></tr></table></figure>

<p>更多信息可以查阅：<a href="http://npm.taobao.org/" target="_blank" rel="noopener">http://npm.taobao.org/</a> 。</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/03/08/react%E5%AE%9E%E7%8E%B0%E7%AE%80%E5%8D%95%E5%8F%8C%E5%90%91%E6%95%B0%E6%8D%AE%E7%BB%91%E5%AE%9A/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://inews.gtimg.com/newsapp_ls/0/12122532695/0">
      <meta itemprop="name" content="Albert Guo">
      <meta itemprop="description" content="郭鹏松的个人博客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Albert Guo">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2019/03/08/react%E5%AE%9E%E7%8E%B0%E7%AE%80%E5%8D%95%E5%8F%8C%E5%90%91%E6%95%B0%E6%8D%AE%E7%BB%91%E5%AE%9A/" class="post-title-link" itemprop="url">react实现简单双向数据绑定</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-03-08 20:26:37" itemprop="dateCreated datePublished" datetime="2019-03-08T20:26:37+08:00">2019-03-08</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-08 20:48:51" itemprop="dateModified" datetime="2020-07-08T20:48:51+08:00">2020-07-08</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/react/" itemprop="url" rel="index"><span itemprop="name">react</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>不同于 vue ，react 本身不支持双向数据绑定，但是可以使用 react 的双向操作 state，来获取设置状态值数据，实现绑定。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">import React, &#123;Component&#125; from &#39;react&#39;;</span><br><span class="line"></span><br><span class="line">export default class Demo extends Component &#123;</span><br><span class="line">    constructor(props) &#123;</span><br><span class="line">        super(props);</span><br><span class="line">        this.state &#x3D; &#123;</span><br><span class="line">            userName:&#39;AlbertGuo&#39;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    getInputValue(state, e) &#123;</span><br><span class="line">        let obj &#x3D; &#123;&#125;</span><br><span class="line">        let iptVal &#x3D; e.target.value</span><br><span class="line">        obj[state] &#x3D; iptVal</span><br><span class="line">        this.setState(obj);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    render() &#123;</span><br><span class="line">        const &#123;</span><br><span class="line">            userName</span><br><span class="line">        &#125; &#x3D; this.state;</span><br><span class="line">        return (&lt;div id&#x3D;&quot;Demo&quot;&gt;</span><br><span class="line">          &lt;input onInput&#x3D;&#123;this.getInputValue.bind(this, &#39;userName&#39;)&#125; placeholder&#x3D;&#39;请输入内容&#39; defaultValue&#x3D;&#123;userName&#125;&#x2F;&gt;</span><br><span class="line">        &lt;&#x2F;div&gt;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/10/15/%E5%A6%82%E4%BD%95%E5%88%A4%E6%96%AD%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%EF%BC%9F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://inews.gtimg.com/newsapp_ls/0/12122532695/0">
      <meta itemprop="name" content="Albert Guo">
      <meta itemprop="description" content="郭鹏松的个人博客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Albert Guo">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2018/10/15/%E5%A6%82%E4%BD%95%E5%88%A4%E6%96%AD%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%EF%BC%9F/" class="post-title-link" itemprop="url">如何判断数据类型？</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-10-15 19:41:39" itemprop="dateCreated datePublished" datetime="2018-10-15T19:41:39+08:00">2018-10-15</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-24 17:46:30" itemprop="dateModified" datetime="2020-07-24T17:46:30+08:00">2020-07-24</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>要弄清楚如何判断数据类型，首先要清楚 JavaScript 到底有哪些数据类型。</p>
<h1 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h1><p>JavaScript 语言的每一个值，都属于某一种数据类型。JavaScript 的数据类型，共有 <code>7</code> 种。</p>
<ul>
<li>数值（<code>number</code>）：整数和小数（比如 <code>1</code> 和 <code>3.14</code>）</li>
<li>字符串（<code>string</code>）：文本（比如 <code>&#39;Hello World&#39;</code>）</li>
<li>布尔值（<code>boolean</code>）：表示真伪的两个特殊值，即 <code>true</code>（真）和 <code>false</code>（假）</li>
<li><code>undefined</code>：表示“未定义”或不存在，即由于目前没有定义，所以此处暂时没有任何值</li>
<li><code>null</code>：表示空值，即此处的值为空</li>
<li><code>Symbol</code>：表示独一无二的值（ES6 新增）</li>
<li>对象（<code>object</code>）：各种值组成的集合</li>
</ul>
<p>对象是最复杂的数据类型，又可以分成几个子类型。</p>
<ul>
<li>狭义的对象（<code>object</code>）</li>
<li>数组（<code>array</code>）</li>
<li>函数（<code>function</code>）</li>
<li>Set（ES6 新增）</li>
<li>Map（ES6 新增）</li>
</ul>
<h1 id="判断数据类型"><a href="#判断数据类型" class="headerlink" title="判断数据类型"></a>判断数据类型</h1><p>JavaScript 有三种方法，可以确定一个值到底是什么类型。</p>
<ul>
<li><code>typeof</code> 运算符（只能精准判断基本数据类型，复杂数据类型判断比较笼统）</li>
<li><code>instanceof</code> 运算符（只能作用于对象，判断复杂数据类型，而且比较笼统，不精准）</li>
<li><code>Object.prototype.toString</code> 方法（推荐使用）</li>
</ul>
<p>声明几个不同类型的变量，用于接下来案例使用。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">'a'</span>;</span><br><span class="line"><span class="keyword">var</span> aa = <span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">'aaa'</span>);</span><br><span class="line"><span class="keyword">var</span> b = <span class="number">123</span>;</span><br><span class="line"><span class="keyword">var</span> c = <span class="literal">true</span>;</span><br><span class="line"><span class="keyword">var</span> d = <span class="literal">undefined</span>;</span><br><span class="line"><span class="keyword">var</span> e = <span class="literal">null</span>;</span><br><span class="line"><span class="keyword">var</span> f = &#123;&#125;;</span><br><span class="line"><span class="keyword">var</span> g = [<span class="string">'2'</span>];</span><br><span class="line"><span class="keyword">var</span> s = <span class="keyword">new</span> <span class="built_in">Set</span>();   <span class="comment">// ES6 新增</span></span><br><span class="line"><span class="keyword">var</span> m = <span class="keyword">new</span> <span class="built_in">Map</span>();   <span class="comment">// ES6 新增</span></span><br><span class="line"><span class="keyword">var</span> sym = <span class="built_in">Symbol</span>(<span class="string">'123'</span>);   <span class="comment">// ES6 新增</span></span><br></pre></td></tr></table></figure>

<p><code>typeof</code> 运算符可以返回一个值的数据类型，只能精准判断基本数据类型，复杂数据类型判断比较笼统。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> a);   <span class="comment">// string</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> g);   <span class="comment">// Object</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> s);   <span class="comment">// Object</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> m);   <span class="comment">// Object</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> sym);   <span class="comment">// symbol</span></span><br></pre></td></tr></table></figure>

<p>数值、字符串、布尔值分别返回 <code>number、string、boolean</code>；函数返回 <code>function</code>、<code>undefined</code> 返回 <code>undefined</code>、对象返回 <code>object</code>、<code>null</code> 返回 <code>object</code>（历史原因）。</p>
<p><code>instanceof</code> 运算符，判断复杂数据类型，而且比较笼统，不精准。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(a <span class="keyword">instanceof</span> <span class="built_in">String</span>);   <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(b <span class="keyword">instanceof</span> <span class="built_in">Number</span>);   <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(aa <span class="keyword">instanceof</span> <span class="built_in">String</span>);   <span class="comment">// true （注意观察和字符串 a 的声明方式）</span></span><br><span class="line"><span class="built_in">console</span>.log(g <span class="keyword">instanceof</span> <span class="built_in">Object</span>);   <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<p><code>Object.prototype.toString</code> 方法，配合 <code>call</code> 方法使用来判断数据类型，推荐使用。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="built_in">Object</span>.prototype.toString.call(a));   <span class="comment">// [object String]</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="built_in">Object</span>.prototype.toString.call(b));   <span class="comment">// [object Number]</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="built_in">Object</span>.prototype.toString.call(g));   <span class="comment">// [object Array]</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="built_in">Object</span>.prototype.toString.call(s));   <span class="comment">// [object Set]</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="built_in">Object</span>.prototype.toString.call(m));   <span class="comment">// [object Map]</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="built_in">Object</span>.prototype.toString.call(sym));   <span class="comment">// [object Symbol]</span></span><br></pre></td></tr></table></figure>


      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  


  
  <nav class="pagination">
    <span class="page-number current">1</span><a class="page-number" href="/page/2/">2</a><a class="extend next" rel="next" href="/page/2/"><i class="fa fa-angle-right" aria-label="下一页"></i></a>
  </nav>



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Albert Guo"
      src="https://inews.gtimg.com/newsapp_ls/0/12122532695/0">
  <p class="site-author-name" itemprop="name">Albert Guo</p>
  <div class="site-description" itemprop="description">郭鹏松的个人博客</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives">
          <span class="site-state-item-count">19</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:albert-guo@outlook.com" title="E-Mail → mailto:albert-guo@outlook.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Albert Guo</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
